﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using SDF.Admin.Extensions;
using SDF.Admin.Models.Common;
using SDF.Admin.Models.Settings;
using SDF.Admin.Models.Projects;
using SDF.Core;
using SDF.Core.Domain;
using SDF.Core.Domain.Blogs;
using SDF.Core.Domain.Catalog;
using SDF.Core.Domain.Common;
using SDF.Core.Domain.Customers;
using SDF.Core.Domain.Directory;
using SDF.Core.Domain.Forums;
using SDF.Core.Domain.Localization;
using SDF.Core.Domain.Media;
using SDF.Core.Domain.News;
using SDF.Core.Domain.Orders;
using SDF.Core.Domain.Security;
using SDF.Core.Domain.Seo;
using SDF.Core.Domain.Shipping;
using SDF.Core.Domain.Tax;
using SDF.Core.Domain.Vendors;
using SDF.Services;
using SDF.Services.Common;
using SDF.Services.Configuration;
using SDF.Services.Customers;
using SDF.Services.Directory;
using SDF.Services.Helpers;
using SDF.Services.Localization;
using SDF.Services.Logging;
using SDF.Services.Media;
using SDF.Services.Orders;
using SDF.Services.Security;
using SDF.Services.Projects;
using SDF.Services.Tax;
using SDF.Web.Framework;
using SDF.Web.Framework.Controllers;
using SDF.Web.Framework.Kendoui;
using SDF.Web.Framework.Localization;
using SDF.Web.Framework.Mvc;
using SDF.Web.Framework.Security;
using SDF.Web.Framework.Security.Captcha;
using SDF.Web.Framework.Themes;

namespace SDF.Admin.Controllers
{
    public partial class SettingController : BaseAdminController
	{
		#region Fields

        private readonly ISettingService _settingService;
        private readonly ICountryService _countryService;
        private readonly IStateProvinceService _stateProvinceService;
        private readonly IAddressService _addressService;
        private readonly ITaxCategoryService _taxCategoryService;
        private readonly ICurrencyService _currencyService;
        private readonly IPictureService _pictureService;
        private readonly ILocalizationService _localizationService;
        private readonly IDateTimeHelper _dateTimeHelper;
        private readonly IOrderService _orderService;
        private readonly IEncryptionService _encryptionService;
        private readonly IThemeProvider _themeProvider;
        private readonly ICustomerService _customerService;
        private readonly ICustomerActivityService _customerActivityService;
        private readonly IPermissionService _permissionService;
        private readonly IFulltextService _fulltextService;
        private readonly IMaintenanceService _maintenanceService;
        private readonly IProjectService _projectService;
        private readonly IWorkContext _workContext;
        private readonly IGenericAttributeService _genericAttributeService;
        private readonly IReturnRequestService _returnRequestService;
        private readonly ILanguageService _languageService;
        private readonly ILocalizedEntityService _localizedEntityService;

        #endregion

        #region Constructors

        public SettingController(ISettingService settingService,
            ICountryService countryService, 
            IStateProvinceService stateProvinceService,
            IAddressService addressService, 
            ITaxCategoryService taxCategoryService,
            ICurrencyService currencyService,
            IPictureService pictureService, 
            ILocalizationService localizationService, 
            IDateTimeHelper dateTimeHelper,
            IOrderService orderService,
            IEncryptionService encryptionService,
            IThemeProvider themeProvider,
            ICustomerService customerService, 
            ICustomerActivityService customerActivityService,
            IPermissionService permissionService,
            IFulltextService fulltextService, 
            IMaintenanceService maintenanceService,
            IProjectService projectService,
            IWorkContext workContext, 
            IGenericAttributeService genericAttributeService,
            IReturnRequestService returnRequestService,
            ILanguageService languageService,
            ILocalizedEntityService localizedEntityService)
        {
            this._settingService = settingService;
            this._countryService = countryService;
            this._stateProvinceService = stateProvinceService;
            this._addressService = addressService;
            this._taxCategoryService = taxCategoryService;
            this._currencyService = currencyService;
            this._pictureService = pictureService;
            this._localizationService = localizationService;
            this._dateTimeHelper = dateTimeHelper;
            this._orderService = orderService;
            this._encryptionService = encryptionService;
            this._themeProvider = themeProvider;
            this._customerService = customerService;
            this._customerActivityService = customerActivityService;
            this._permissionService = permissionService;
            this._fulltextService = fulltextService;
            this._maintenanceService = maintenanceService;
            this._projectService = projectService;
            this._workContext = workContext;
            this._genericAttributeService = genericAttributeService;
            this._returnRequestService = returnRequestService;
            this._languageService = languageService;
            this._localizedEntityService = localizedEntityService;
        }

        #endregion

        #region Utilities

        [NonAction]
        protected virtual void UpdateLocales(ReturnRequestReason rrr, ReturnRequestReasonModel model)
        {
            foreach (var localized in model.Locales)
            {
                _localizedEntityService.SaveLocalizedValue(rrr,
                                                               x => x.Name,
                                                               localized.Name,
                                                               localized.LanguageId);
            }
        }

        [NonAction]
        protected virtual void UpdateLocales(ReturnRequestAction rra, ReturnRequestActionModel model)
        {
            foreach (var localized in model.Locales)
            {
                _localizedEntityService.SaveLocalizedValue(rra,
                                                               x => x.Name,
                                                               localized.Name,
                                                               localized.LanguageId);
            }
        }

        #endregion

        #region Methods

        [ChildActionOnly]
        public ActionResult Mode(string modeName = "settings-advanced-mode")
        {
            var model = new ModeModel()
            {
                ModeName = modeName,
                Enabled = _workContext.CurrentCustomer.GetAttribute<bool>(modeName)
            };
            return PartialView(model);
        }

        [ChildActionOnly]
        public ActionResult ProjectScopeConfiguration()
        {
            var allProjects = _projectService.GetAllProjects();
            if (allProjects.Count < 2)
                return Content("");

            var model = new ProjectScopeConfigurationModel();
            foreach (var s in allProjects)
            {
                model.Projects.Add(new ProjectModel
                {
                    Id = s.Id,
                    Name = s.Name
                });
            }
            model.ProjectId = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);

            return PartialView(model);
        }
        public ActionResult ChangeProjectScopeConfiguration(int projectid, string returnUrl = "")
        {
            var project = _projectService.GetProjectById(projectid);
            if (project != null || projectid == 0)
            {
                _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
                    SystemCustomerAttributeNames.AdminAreaProjectScopeConfiguration, projectid);
            }

            //home page
            if (String.IsNullOrEmpty(returnUrl))
                returnUrl = Url.Action("Index", "Home", new { area = "Admin" });
            //prevent open redirection attack
            if (!Url.IsLocalUrl(returnUrl))
                return RedirectToAction("Index", "Home", new { area = "Admin" });
            return Redirect(returnUrl);
        }

        public ActionResult Blog()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var blogSettings = _settingService.LoadSetting<BlogSettings>(ProjectScope);
            var model = blogSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.Enabled_OverrideForProject = _settingService.SettingExists(blogSettings, x => x.Enabled, ProjectScope);
                model.PostsPageSize_OverrideForProject = _settingService.SettingExists(blogSettings, x => x.PostsPageSize, ProjectScope);
                model.AllowNotRegisteredUsersToLeaveComments_OverrideForProject = _settingService.SettingExists(blogSettings, x => x.AllowNotRegisteredUsersToLeaveComments, ProjectScope);
                model.NotifyAboutNewBlogComments_OverrideForProject = _settingService.SettingExists(blogSettings, x => x.NotifyAboutNewBlogComments, ProjectScope);
                model.NumberOfTags_OverrideForProject = _settingService.SettingExists(blogSettings, x => x.NumberOfTags, ProjectScope);
                model.ShowHeaderRssUrl_OverrideForProject = _settingService.SettingExists(blogSettings, x => x.ShowHeaderRssUrl, ProjectScope);
            }

            return View(model);
        }
        [HttpPost]
        public ActionResult Blog(BlogSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var blogSettings = _settingService.LoadSetting<BlogSettings>(ProjectScope);
            blogSettings = model.ToEntity(blogSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerProject(blogSettings, x => x.Enabled, model.Enabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(blogSettings, x => x.PostsPageSize, model.PostsPageSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(blogSettings, x => x.AllowNotRegisteredUsersToLeaveComments, model.AllowNotRegisteredUsersToLeaveComments_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(blogSettings, x => x.NotifyAboutNewBlogComments, model.NotifyAboutNewBlogComments_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(blogSettings, x => x.NumberOfTags, model.NumberOfTags_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(blogSettings, x => x.ShowHeaderRssUrl, model.ShowHeaderRssUrl_OverrideForProject, ProjectScope, false);
            
            //now clear settings cache
            _settingService.ClearCache();

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Blog");
        }




        public ActionResult Vendor()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var vendorSettings = _settingService.LoadSetting<VendorSettings>(ProjectScope);
            var model = vendorSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.VendorsBlockItemsToDisplay_OverrideForProject = _settingService.SettingExists(vendorSettings, x => x.VendorsBlockItemsToDisplay, ProjectScope);
                model.ShowVendorOnProductDetailsPage_OverrideForProject = _settingService.SettingExists(vendorSettings, x => x.ShowVendorOnProductDetailsPage, ProjectScope);
                model.AllowCustomersToContactVendors_OverrideForProject = _settingService.SettingExists(vendorSettings, x => x.AllowCustomersToContactVendors, ProjectScope);
                model.AllowCustomersToApplyForVendorAccount_OverrideForProject = _settingService.SettingExists(vendorSettings, x => x.AllowCustomersToApplyForVendorAccount, ProjectScope);
                model.AllowSearchByVendor_OverrideForProject = _settingService.SettingExists(vendorSettings, x => x.AllowSearchByVendor, ProjectScope);
                model.AllowVendorsToEditInfo_OverrideForProject = _settingService.SettingExists(vendorSettings, x => x.AllowVendorsToEditInfo, ProjectScope);
                model.NotifyProjectOwnerAboutVendorInformationChange_OverrideForProject = _settingService.SettingExists(vendorSettings, x => x.NotifyProjectOwnerAboutVendorInformationChange, ProjectScope);
                model.MaximumProductNumber_OverrideForProject = _settingService.SettingExists(vendorSettings, x => x.MaximumProductNumber, ProjectScope);
            }

            return View(model);
        }
        [HttpPost]
        public ActionResult Vendor(VendorSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var vendorSettings = _settingService.LoadSetting<VendorSettings>(ProjectScope);
            vendorSettings = model.ToEntity(vendorSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerProject(vendorSettings, x => x.VendorsBlockItemsToDisplay, model.VendorsBlockItemsToDisplay_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(vendorSettings, x => x.ShowVendorOnProductDetailsPage, model.ShowVendorOnProductDetailsPage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(vendorSettings, x => x.AllowCustomersToContactVendors, model.AllowCustomersToContactVendors_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(vendorSettings, x => x.AllowCustomersToApplyForVendorAccount, model.AllowCustomersToApplyForVendorAccount_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(vendorSettings, x => x.AllowSearchByVendor, model.AllowSearchByVendor_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(vendorSettings, x => x.AllowVendorsToEditInfo, model.AllowVendorsToEditInfo_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(vendorSettings, x => x.NotifyProjectOwnerAboutVendorInformationChange, model.NotifyProjectOwnerAboutVendorInformationChange_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(vendorSettings, x => x.MaximumProductNumber, model.MaximumProductNumber_OverrideForProject, ProjectScope, false);

            //now clear settings cache
            _settingService.ClearCache();

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Vendor");
        }




        public ActionResult Forum()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var forumSettings = _settingService.LoadSetting<ForumSettings>(ProjectScope);
            var model = forumSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.ForumsEnabled_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.ForumsEnabled, ProjectScope);
                model.RelativeDateTimeFormattingEnabled_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.RelativeDateTimeFormattingEnabled, ProjectScope);
                model.ShowCustomersPostCount_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.ShowCustomersPostCount, ProjectScope);
                model.AllowGuestsToCreatePosts_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.AllowGuestsToCreatePosts, ProjectScope);
                model.AllowGuestsToCreateTopics_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.AllowGuestsToCreateTopics, ProjectScope);
                model.AllowCustomersToEditPosts_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.AllowCustomersToEditPosts, ProjectScope);
                model.AllowCustomersToDeletePosts_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.AllowCustomersToDeletePosts, ProjectScope);
                model.AllowPostVoting_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.AllowPostVoting, ProjectScope);
                model.MaxVotesPerDay_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.MaxVotesPerDay, ProjectScope);
                model.AllowCustomersToManageSubscriptions_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.AllowCustomersToManageSubscriptions, ProjectScope);
                model.TopicsPageSize_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.TopicsPageSize, ProjectScope);
                model.PostsPageSize_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.PostsPageSize, ProjectScope);
                model.ForumEditor_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.ForumEditor, ProjectScope);
                model.SignaturesEnabled_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.SignaturesEnabled, ProjectScope);
                model.AllowPrivateMessages_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.AllowPrivateMessages, ProjectScope);
                model.ShowAlertForPM_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.ShowAlertForPM, ProjectScope);
                model.NotifyAboutPrivateMessages_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.NotifyAboutPrivateMessages, ProjectScope);
                model.ActiveDiscussionsFeedEnabled_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.ActiveDiscussionsFeedEnabled, ProjectScope);
                model.ActiveDiscussionsFeedCount_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.ActiveDiscussionsFeedCount, ProjectScope);
                model.ForumFeedsEnabled_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.ForumFeedsEnabled, ProjectScope);
                model.ForumFeedCount_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.ForumFeedCount, ProjectScope);
                model.SearchResultsPageSize_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.SearchResultsPageSize, ProjectScope);
                model.ActiveDiscussionsPageSize_OverrideForProject = _settingService.SettingExists(forumSettings, x => x.ActiveDiscussionsPageSize, ProjectScope);
            }
            model.ForumEditorValues = forumSettings.ForumEditor.ToSelectList();

            return View(model);
        }
        [HttpPost]
        public ActionResult Forum(ForumSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var forumSettings = _settingService.LoadSetting<ForumSettings>(ProjectScope);
            forumSettings = model.ToEntity(forumSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.ForumsEnabled, model.ForumsEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.RelativeDateTimeFormattingEnabled, model.RelativeDateTimeFormattingEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.ShowCustomersPostCount, model.ShowCustomersPostCount_OverrideForProject , ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.AllowGuestsToCreatePosts, model.AllowGuestsToCreatePosts_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.AllowGuestsToCreateTopics, model.AllowGuestsToCreateTopics_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.AllowCustomersToEditPosts, model.AllowCustomersToEditPosts_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.AllowCustomersToDeletePosts, model.AllowCustomersToDeletePosts_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.AllowPostVoting, model.AllowPostVoting_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.MaxVotesPerDay, model.MaxVotesPerDay_OverrideForProject , ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.AllowCustomersToManageSubscriptions, model.AllowCustomersToManageSubscriptions_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.TopicsPageSize, model.TopicsPageSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.PostsPageSize, model.PostsPageSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.ForumEditor, model.ForumEditor_OverrideForProject , ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.SignaturesEnabled, model.SignaturesEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.AllowPrivateMessages, model.AllowPrivateMessages_OverrideForProject , ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.ShowAlertForPM, model.ShowAlertForPM_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.NotifyAboutPrivateMessages, model.NotifyAboutPrivateMessages_OverrideForProject , ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.ActiveDiscussionsFeedEnabled, model.ActiveDiscussionsFeedEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.ActiveDiscussionsFeedCount, model.ActiveDiscussionsFeedCount_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.ForumFeedsEnabled, model.ForumFeedsEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.ForumFeedCount, model.ForumFeedCount_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.SearchResultsPageSize, model.SearchResultsPageSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(forumSettings, x => x.ActiveDiscussionsPageSize, model.ActiveDiscussionsPageSize_OverrideForProject, ProjectScope, false);
            
            //now clear settings cache
            _settingService.ClearCache();

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Forum");
        }




        public ActionResult News()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var newsSettings = _settingService.LoadSetting<NewsSettings>(ProjectScope);
            var model = newsSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.Enabled_OverrideForProject = _settingService.SettingExists(newsSettings, x => x.Enabled, ProjectScope);
                model.AllowNotRegisteredUsersToLeaveComments_OverrideForProject = _settingService.SettingExists(newsSettings, x => x.AllowNotRegisteredUsersToLeaveComments, ProjectScope);
                model.NotifyAboutNewNewsComments_OverrideForProject = _settingService.SettingExists(newsSettings, x => x.NotifyAboutNewNewsComments, ProjectScope);
                model.ShowNewsOnMainPage_OverrideForProject = _settingService.SettingExists(newsSettings, x => x.ShowNewsOnMainPage, ProjectScope);
                model.MainPageNewsCount_OverrideForProject = _settingService.SettingExists(newsSettings, x => x.MainPageNewsCount, ProjectScope);
                model.NewsArchivePageSize_OverrideForProject = _settingService.SettingExists(newsSettings, x => x.NewsArchivePageSize, ProjectScope);
                model.ShowHeaderRssUrl_OverrideForProject = _settingService.SettingExists(newsSettings, x => x.ShowHeaderRssUrl, ProjectScope);
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult News(NewsSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var newsSettings = _settingService.LoadSetting<NewsSettings>(ProjectScope);
            newsSettings = model.ToEntity(newsSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerProject(newsSettings, x => x.Enabled, model.Enabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(newsSettings, x => x.AllowNotRegisteredUsersToLeaveComments, model.AllowNotRegisteredUsersToLeaveComments_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(newsSettings, x => x.NotifyAboutNewNewsComments, model.NotifyAboutNewNewsComments_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(newsSettings, x => x.ShowNewsOnMainPage, model.ShowNewsOnMainPage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(newsSettings, x => x.MainPageNewsCount, model.MainPageNewsCount_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(newsSettings, x => x.NewsArchivePageSize, model.NewsArchivePageSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(newsSettings, x => x.ShowHeaderRssUrl, model.ShowHeaderRssUrl_OverrideForProject, ProjectScope, false);
            
            //now clear settings cache
            _settingService.ClearCache();


            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("News");
        }




        public ActionResult Shipping()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var shippingSettings = _settingService.LoadSetting<ShippingSettings>(ProjectScope);
            var model = shippingSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.ShipToSameAddress_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.ShipToSameAddress, ProjectScope);
                model.AllowPickUpInProject_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.AllowPickUpInProject, ProjectScope);
                model.DisplayPickupPointsOnMap_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.DisplayPickupPointsOnMap, ProjectScope);
                model.GoogleMapsApiKey_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.GoogleMapsApiKey, ProjectScope);
                model.UseWarehouseLocation_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.UseWarehouseLocation, ProjectScope);
                model.NotifyCustomerAboutShippingFromMultipleLocations_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.NotifyCustomerAboutShippingFromMultipleLocations, ProjectScope);
                model.FreeShippingOverXEnabled_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.FreeShippingOverXEnabled, ProjectScope);
                model.FreeShippingOverXValue_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.FreeShippingOverXValue, ProjectScope);
                model.FreeShippingOverXIncludingTax_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.FreeShippingOverXIncludingTax, ProjectScope);
                model.EstimateShippingEnabled_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.EstimateShippingEnabled, ProjectScope);
                model.DisplayShipmentEventsToCustomers_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.DisplayShipmentEventsToCustomers, ProjectScope);
                model.DisplayShipmentEventsToProjectOwner_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.DisplayShipmentEventsToProjectOwner, ProjectScope);
                model.BypassShippingMethodSelectionIfOnlyOne_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.BypassShippingMethodSelectionIfOnlyOne, ProjectScope);
                model.ShippingOriginAddress_OverrideForProject = _settingService.SettingExists(shippingSettings, x => x.ShippingOriginAddressId, ProjectScope);
            }
            //shipping origin
            var originAddress = shippingSettings.ShippingOriginAddressId > 0
                                     ? _addressService.GetAddressById(shippingSettings.ShippingOriginAddressId)
                                     : null;
            if (originAddress != null)
                model.ShippingOriginAddress = originAddress.ToModel();
            else
                model.ShippingOriginAddress = new AddressModel();

            model.ShippingOriginAddress.AvailableCountries.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0" });
            foreach (var c in _countryService.GetAllCountries(showHidden: true))
                model.ShippingOriginAddress.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString(), Selected = (originAddress != null && c.Id == originAddress.CountryId) });

            var states = originAddress != null && originAddress.Country != null ? _stateProvinceService.GetStateProvincesByCountryId(originAddress.Country.Id, showHidden: true).ToList() : new List<StateProvince>();
            if (states.Any())
            {
                foreach (var s in states)
                    model.ShippingOriginAddress.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString(), Selected = (s.Id == originAddress.StateProvinceId) });
            }
            else
                model.ShippingOriginAddress.AvailableStates.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0" });
            model.ShippingOriginAddress.CountryEnabled = true;
            model.ShippingOriginAddress.StateProvinceEnabled = true;
            model.ShippingOriginAddress.CityEnabled = true;
            model.ShippingOriginAddress.StreetAddressEnabled = true;
            model.ShippingOriginAddress.ZipPostalCodeEnabled = true;
            model.ShippingOriginAddress.ZipPostalCodeRequired = true;
            
            return View(model);
        }
        [HttpPost]
        public ActionResult Shipping(ShippingSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var shippingSettings = _settingService.LoadSetting<ShippingSettings>(ProjectScope);
            shippingSettings = model.ToEntity(shippingSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.ShipToSameAddress, model.ShipToSameAddress_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.AllowPickUpInProject, model.AllowPickUpInProject_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.DisplayPickupPointsOnMap, model.DisplayPickupPointsOnMap_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.GoogleMapsApiKey, model.GoogleMapsApiKey_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.UseWarehouseLocation, model.UseWarehouseLocation_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.NotifyCustomerAboutShippingFromMultipleLocations, model.NotifyCustomerAboutShippingFromMultipleLocations_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.FreeShippingOverXEnabled, model.FreeShippingOverXEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.FreeShippingOverXValue, model.FreeShippingOverXValue_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.FreeShippingOverXIncludingTax, model.FreeShippingOverXIncludingTax_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.EstimateShippingEnabled, model.EstimateShippingEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.DisplayShipmentEventsToCustomers, model.DisplayShipmentEventsToCustomers_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.DisplayShipmentEventsToProjectOwner, model.DisplayShipmentEventsToProjectOwner_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shippingSettings, x => x.BypassShippingMethodSelectionIfOnlyOne, model.BypassShippingMethodSelectionIfOnlyOne_OverrideForProject, ProjectScope, false);
            
            if (model.ShippingOriginAddress_OverrideForProject || ProjectScope == 0)
            {
                //update address
                var addressId = _settingService.SettingExists(shippingSettings, x => x.ShippingOriginAddressId, ProjectScope) ?
                    shippingSettings.ShippingOriginAddressId : 0;
                var originAddress = _addressService.GetAddressById(addressId) ??
                    new Address
                    {
                        CreatedOnUtc = DateTime.UtcNow,
                    };
                //update ID manually (in case we're in multi-project configuration mode it'll be set to the shared one)
                model.ShippingOriginAddress.Id = addressId;
                originAddress = model.ShippingOriginAddress.ToEntity(originAddress);
                if (originAddress.Id > 0)
                    _addressService.UpdateAddress(originAddress);
                else
                    _addressService.InsertAddress(originAddress);
                shippingSettings.ShippingOriginAddressId = originAddress.Id;

                _settingService.SaveSetting(shippingSettings, x => x.ShippingOriginAddressId, ProjectScope, false);
            }
            else if (ProjectScope > 0)
                _settingService.DeleteSetting(shippingSettings, x => x.ShippingOriginAddressId, ProjectScope);


            //now clear settings cache
            _settingService.ClearCache();


            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Shipping");
        }




        public ActionResult Tax()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var taxSettings = _settingService.LoadSetting<TaxSettings>(ProjectScope);
            var model = taxSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.PricesIncludeTax_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.PricesIncludeTax, ProjectScope);
                model.AllowCustomersToSelectTaxDisplayType_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.AllowCustomersToSelectTaxDisplayType, ProjectScope);
                model.TaxDisplayType_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.TaxDisplayType, ProjectScope);
                model.DisplayTaxSuffix_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.DisplayTaxSuffix, ProjectScope);
                model.DisplayTaxRates_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.DisplayTaxRates, ProjectScope);
                model.HideZeroTax_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.HideZeroTax, ProjectScope);
                model.HideTaxInOrderSummary_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.HideTaxInOrderSummary, ProjectScope);
                model.ForceTaxExclusionFromOrderSubtotal_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.ForceTaxExclusionFromOrderSubtotal, ProjectScope);
                model.TaxBasedOn_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.TaxBasedOn, ProjectScope);
                model.DefaultTaxAddress_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.DefaultTaxAddressId, ProjectScope);
                model.ShippingIsTaxable_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.ShippingIsTaxable, ProjectScope);
                model.ShippingPriceIncludesTax_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.ShippingPriceIncludesTax, ProjectScope);
                model.ShippingTaxClassId_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.ShippingTaxClassId, ProjectScope);
                model.PaymentMethodAdditionalFeeIsTaxable_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.PaymentMethodAdditionalFeeIsTaxable, ProjectScope);
                model.PaymentMethodAdditionalFeeIncludesTax_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.PaymentMethodAdditionalFeeIncludesTax, ProjectScope);
                model.PaymentMethodAdditionalFeeTaxClassId_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.PaymentMethodAdditionalFeeTaxClassId, ProjectScope);
                model.EuVatEnabled_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.EuVatEnabled, ProjectScope);
                model.EuVatShopCountryId_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.EuVatShopCountryId, ProjectScope);
                model.EuVatAllowVatExemption_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.EuVatAllowVatExemption, ProjectScope);
                model.EuVatUseWebService_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.EuVatUseWebService, ProjectScope);
                model.EuVatAssumeValid_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.EuVatAssumeValid, ProjectScope);
                model.EuVatEmailAdminWhenNewVatSubmitted_OverrideForProject = _settingService.SettingExists(taxSettings, x => x.EuVatEmailAdminWhenNewVatSubmitted, ProjectScope);
            }

            model.TaxBasedOnValues = taxSettings.TaxBasedOn.ToSelectList();
            model.TaxDisplayTypeValues = taxSettings.TaxDisplayType.ToSelectList();

            //tax categories
            var taxCategories = _taxCategoryService.GetAllTaxCategories();
            model.ShippingTaxCategories.Add(new SelectListItem { Text = "---", Value = "0" });
            foreach (var tc in taxCategories)
                model.ShippingTaxCategories.Add(new SelectListItem { Text = tc.Name, Value = tc.Id.ToString(), Selected = tc.Id == taxSettings.ShippingTaxClassId });
            model.PaymentMethodAdditionalFeeTaxCategories.Add(new SelectListItem { Text = "---", Value = "0" });
            foreach (var tc in taxCategories)
                model.PaymentMethodAdditionalFeeTaxCategories.Add(new SelectListItem { Text = tc.Name, Value = tc.Id.ToString(), Selected = tc.Id == taxSettings.PaymentMethodAdditionalFeeTaxClassId });

            //EU VAT countries
            model.EuVatShopCountries.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0" });
            foreach (var c in _countryService.GetAllCountries(showHidden: true))
                model.EuVatShopCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString(), Selected = c.Id == taxSettings.EuVatShopCountryId });

            //default tax address
            var defaultAddress = taxSettings.DefaultTaxAddressId > 0
                                     ? _addressService.GetAddressById(taxSettings.DefaultTaxAddressId)
                                     : null;
            if (defaultAddress != null)
                model.DefaultTaxAddress = defaultAddress.ToModel();
            else
                model.DefaultTaxAddress = new AddressModel();

            model.DefaultTaxAddress.AvailableCountries.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0" });
            foreach (var c in _countryService.GetAllCountries(showHidden: true))
                model.DefaultTaxAddress.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString(), Selected = (defaultAddress != null && c.Id == defaultAddress.CountryId) });

            var states = defaultAddress != null && defaultAddress.Country != null ? _stateProvinceService.GetStateProvincesByCountryId(defaultAddress.Country.Id, showHidden: true).ToList() : new List<StateProvince>();
            if (states.Any())
            {
                foreach (var s in states)
                    model.DefaultTaxAddress.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString(), Selected = (s.Id == defaultAddress.StateProvinceId) });
            }
            else
                model.DefaultTaxAddress.AvailableStates.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0" });
            model.DefaultTaxAddress.CountryEnabled = true;
            model.DefaultTaxAddress.StateProvinceEnabled = true;
            model.DefaultTaxAddress.ZipPostalCodeEnabled = true;
            model.DefaultTaxAddress.ZipPostalCodeRequired = true;

            return View(model);
        }
        [HttpPost]
        public ActionResult Tax(TaxSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var taxSettings = _settingService.LoadSetting<TaxSettings>(ProjectScope);
            taxSettings = model.ToEntity(taxSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.PricesIncludeTax, model.PricesIncludeTax_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.AllowCustomersToSelectTaxDisplayType, model.AllowCustomersToSelectTaxDisplayType_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.TaxDisplayType, model.TaxDisplayType_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.DisplayTaxSuffix, model.DisplayTaxSuffix_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.DisplayTaxRates, model.DisplayTaxRates_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.HideZeroTax, model.HideZeroTax_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.HideTaxInOrderSummary, model.HideTaxInOrderSummary_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.ForceTaxExclusionFromOrderSubtotal, model.ForceTaxExclusionFromOrderSubtotal_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.TaxBasedOn, model.TaxBasedOn_OverrideForProject, ProjectScope, false);


            if (model.DefaultTaxAddress_OverrideForProject || ProjectScope == 0)
            {
                //update address
                var addressId = _settingService.SettingExists(taxSettings, x => x.DefaultTaxAddressId, ProjectScope) ?
                    taxSettings.DefaultTaxAddressId : 0;
                var originAddress = _addressService.GetAddressById(addressId) ??
                    new Address
                    {
                        CreatedOnUtc = DateTime.UtcNow,
                    };
                //update ID manually (in case we're in multi-project configuration mode it'll be set to the shared one)
                model.DefaultTaxAddress.Id = addressId;
                originAddress = model.DefaultTaxAddress.ToEntity(originAddress);
                if (originAddress.Id > 0)
                    _addressService.UpdateAddress(originAddress);
                else
                    _addressService.InsertAddress(originAddress);
                taxSettings.DefaultTaxAddressId = originAddress.Id;

                _settingService.SaveSetting(taxSettings, x => x.DefaultTaxAddressId, ProjectScope, false);
            }
            else if (ProjectScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.DefaultTaxAddressId, ProjectScope);

            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.ShippingIsTaxable, model.ShippingIsTaxable_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.ShippingPriceIncludesTax, model.ShippingPriceIncludesTax_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.ShippingTaxClassId, model.ShippingTaxClassId_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.PaymentMethodAdditionalFeeIsTaxable, model.PaymentMethodAdditionalFeeIsTaxable_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.PaymentMethodAdditionalFeeIncludesTax, model.PaymentMethodAdditionalFeeIncludesTax_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.PaymentMethodAdditionalFeeTaxClassId, model.PaymentMethodAdditionalFeeTaxClassId_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.EuVatEnabled, model.EuVatEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.EuVatShopCountryId, model.EuVatShopCountryId_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.EuVatAllowVatExemption, model.EuVatAllowVatExemption_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.EuVatUseWebService, model.EuVatUseWebService_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.EuVatAssumeValid, model.EuVatAssumeValid_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(taxSettings, x => x.EuVatEmailAdminWhenNewVatSubmitted, model.EuVatEmailAdminWhenNewVatSubmitted_OverrideForProject, ProjectScope, false);
            
            //now clear settings cache
            _settingService.ClearCache();

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Tax");
        }




        public ActionResult Catalog()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var catalogSettings = _settingService.LoadSetting<CatalogSettings>(ProjectScope);
            var model = catalogSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.AllowViewUnpublishedProductPage_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.AllowViewUnpublishedProductPage, ProjectScope);
                model.DisplayDiscontinuedMessageForUnpublishedProducts_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.DisplayDiscontinuedMessageForUnpublishedProducts, ProjectScope);
                model.ShowProductSku_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowProductSku, ProjectScope);
                model.ShowManufacturerPartNumber_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowManufacturerPartNumber, ProjectScope);
                model.ShowGtin_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowGtin, ProjectScope);
                model.ShowFreeShippingNotification_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowFreeShippingNotification, ProjectScope);
                model.AllowProductSorting_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.AllowProductSorting, ProjectScope);
                model.AllowProductViewModeChanging_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.AllowProductViewModeChanging, ProjectScope);
                model.ShowProductsFromSubcategories_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowProductsFromSubcategories, ProjectScope);
                model.ShowCategoryProductNumber_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowCategoryProductNumber, ProjectScope);
                model.ShowCategoryProductNumberIncludingSubcategories_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowCategoryProductNumberIncludingSubcategories, ProjectScope);
                model.CategoryBreadcrumbEnabled_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.CategoryBreadcrumbEnabled, ProjectScope);
                model.ShowShareButton_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowShareButton, ProjectScope);
                model.PageShareCode_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.PageShareCode, ProjectScope);
                model.ProductReviewsMustBeApproved_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ProductReviewsMustBeApproved, ProjectScope);
                model.AllowAnonymousUsersToReviewProduct_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.AllowAnonymousUsersToReviewProduct, ProjectScope);
                model.NotifyProjectOwnerAboutNewProductReviews_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.NotifyProjectOwnerAboutNewProductReviews, ProjectScope);
                model.EmailAFriendEnabled_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.EmailAFriendEnabled, ProjectScope);
                model.AllowAnonymousUsersToEmailAFriend_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.AllowAnonymousUsersToEmailAFriend, ProjectScope);
                model.RecentlyViewedProductsNumber_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.RecentlyViewedProductsNumber, ProjectScope);
                model.RecentlyViewedProductsEnabled_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.RecentlyViewedProductsEnabled, ProjectScope);
                model.NewProductsNumber_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.NewProductsNumber, ProjectScope);
                model.NewProductsEnabled_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.NewProductsEnabled, ProjectScope);
                model.CompareProductsEnabled_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.CompareProductsEnabled, ProjectScope);
                model.ShowBestsellersOnHomepage_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowBestsellersOnHomepage, ProjectScope);
                model.NumberOfBestsellersOnHomepage_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.NumberOfBestsellersOnHomepage, ProjectScope);
                model.SearchPageProductsPerPage_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.SearchPageProductsPerPage, ProjectScope);
                model.SearchPageAllowCustomersToSelectPageSize_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.SearchPageAllowCustomersToSelectPageSize, ProjectScope);
                model.SearchPagePageSizeOptions_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.SearchPagePageSizeOptions, ProjectScope);
                model.ProductSearchAutoCompleteEnabled_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ProductSearchAutoCompleteEnabled, ProjectScope);
                model.ProductSearchAutoCompleteNumberOfProducts_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ProductSearchAutoCompleteNumberOfProducts, ProjectScope);
                model.ShowProductImagesInSearchAutoComplete_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowProductImagesInSearchAutoComplete, ProjectScope);
                model.ProductSearchTermMinimumLength_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ProductSearchTermMinimumLength, ProjectScope);
                model.ProductsAlsoPurchasedEnabled_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ProductsAlsoPurchasedEnabled, ProjectScope);
                model.ProductsAlsoPurchasedNumber_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ProductsAlsoPurchasedNumber, ProjectScope);
                model.NumberOfProductTags_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.NumberOfProductTags, ProjectScope);
                model.ProductsByTagPageSize_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ProductsByTagPageSize, ProjectScope);
                model.ProductsByTagAllowCustomersToSelectPageSize_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ProductsByTagAllowCustomersToSelectPageSize, ProjectScope);
                model.ProductsByTagPageSizeOptions_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ProductsByTagPageSizeOptions, ProjectScope);
                model.IncludeShortDescriptionInCompareProducts_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.IncludeShortDescriptionInCompareProducts, ProjectScope);
                model.IncludeFullDescriptionInCompareProducts_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.IncludeFullDescriptionInCompareProducts, ProjectScope);
                model.ManufacturersBlockItemsToDisplay_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ManufacturersBlockItemsToDisplay, ProjectScope);
                model.DisplayTaxShippingInfoFooter_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.DisplayTaxShippingInfoFooter, ProjectScope);
                model.DisplayTaxShippingInfoProductDetailsPage_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.DisplayTaxShippingInfoProductDetailsPage, ProjectScope);
                model.DisplayTaxShippingInfoProductBoxes_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.DisplayTaxShippingInfoProductBoxes, ProjectScope);
                model.DisplayTaxShippingInfoShoppingCart_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.DisplayTaxShippingInfoShoppingCart, ProjectScope);
                model.DisplayTaxShippingInfoWishlist_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.DisplayTaxShippingInfoWishlist, ProjectScope);
                model.DisplayTaxShippingInfoOrderDetailsPage_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.DisplayTaxShippingInfoOrderDetailsPage, ProjectScope);
                model.ShowProductReviewsPerProject_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowProductReviewsPerProject, ProjectScope);
                model.ShowProductReviewsOnAccountPage_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ShowProductReviewsTabOnAccountPage, ProjectScope);
                model.ProductReviewsPageSizeOnAccountPage_OverrideForProject = _settingService.SettingExists(catalogSettings, x=> x.ProductReviewsPageSizeOnAccountPage, ProjectScope);
                model.ExportImportProductAttributes_OverrideForProject = _settingService.SettingExists(catalogSettings, x => x.ExportImportProductAttributes, ProjectScope);
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult Catalog(CatalogSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var catalogSettings = _settingService.LoadSetting<CatalogSettings>(ProjectScope);
            catalogSettings = model.ToEntity(catalogSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.AllowViewUnpublishedProductPage, model.AllowViewUnpublishedProductPage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.DisplayDiscontinuedMessageForUnpublishedProducts, model.DisplayDiscontinuedMessageForUnpublishedProducts_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowProductSku, model.ShowProductSku_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowManufacturerPartNumber, model.ShowManufacturerPartNumber_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowGtin, model.ShowGtin_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowFreeShippingNotification, model.ShowFreeShippingNotification_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.AllowProductSorting, model.AllowProductSorting_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.AllowProductViewModeChanging, model.AllowProductViewModeChanging_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowProductsFromSubcategories, model.ShowProductsFromSubcategories_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowCategoryProductNumber, model.ShowCategoryProductNumber_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowCategoryProductNumberIncludingSubcategories, model.ShowCategoryProductNumberIncludingSubcategories_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.CategoryBreadcrumbEnabled, model.CategoryBreadcrumbEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowShareButton, model.ShowShareButton_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.PageShareCode, model.PageShareCode_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ProductReviewsMustBeApproved, model.ProductReviewsMustBeApproved_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.AllowAnonymousUsersToReviewProduct, model.AllowAnonymousUsersToReviewProduct_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.NotifyProjectOwnerAboutNewProductReviews, model.NotifyProjectOwnerAboutNewProductReviews_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.EmailAFriendEnabled, model.EmailAFriendEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.AllowAnonymousUsersToEmailAFriend, model.AllowAnonymousUsersToEmailAFriend_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.RecentlyViewedProductsNumber, model.RecentlyViewedProductsNumber_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.RecentlyViewedProductsEnabled, model.RecentlyViewedProductsEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.NewProductsNumber, model.NewProductsNumber_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.NewProductsEnabled, model.NewProductsEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.CompareProductsEnabled, model.CompareProductsEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowBestsellersOnHomepage, model.ShowBestsellersOnHomepage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.NumberOfBestsellersOnHomepage, model.NumberOfBestsellersOnHomepage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.SearchPageProductsPerPage, model.SearchPageProductsPerPage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.SearchPageAllowCustomersToSelectPageSize, model.SearchPageAllowCustomersToSelectPageSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.SearchPagePageSizeOptions, model.SearchPagePageSizeOptions_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ProductSearchAutoCompleteEnabled, model.ProductSearchAutoCompleteEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ProductSearchAutoCompleteNumberOfProducts, model.ProductSearchAutoCompleteNumberOfProducts_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowProductImagesInSearchAutoComplete, model.ShowProductImagesInSearchAutoComplete_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ProductSearchTermMinimumLength, model.ProductSearchTermMinimumLength_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ProductsAlsoPurchasedEnabled, model.ProductsAlsoPurchasedEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ProductsAlsoPurchasedNumber, model.ProductsAlsoPurchasedNumber_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.NumberOfProductTags, model.NumberOfProductTags_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ProductsByTagPageSize, model.ProductsByTagPageSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ProductsByTagAllowCustomersToSelectPageSize, model.ProductsByTagAllowCustomersToSelectPageSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ProductsByTagPageSizeOptions, model.ProductsByTagPageSizeOptions_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.IncludeShortDescriptionInCompareProducts, model.IncludeShortDescriptionInCompareProducts_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.IncludeFullDescriptionInCompareProducts, model.IncludeFullDescriptionInCompareProducts_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ManufacturersBlockItemsToDisplay, model.ManufacturersBlockItemsToDisplay_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.DisplayTaxShippingInfoFooter, model.DisplayTaxShippingInfoFooter_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.DisplayTaxShippingInfoProductDetailsPage, model.DisplayTaxShippingInfoProductDetailsPage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.DisplayTaxShippingInfoProductBoxes, model.DisplayTaxShippingInfoProductBoxes_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.DisplayTaxShippingInfoShoppingCart, model.DisplayTaxShippingInfoShoppingCart_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.DisplayTaxShippingInfoWishlist, model.DisplayTaxShippingInfoWishlist_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.DisplayTaxShippingInfoOrderDetailsPage, model.DisplayTaxShippingInfoOrderDetailsPage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowProductReviewsPerProject, model.ShowProductReviewsPerProject_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ShowProductReviewsTabOnAccountPage, model.ShowProductReviewsOnAccountPage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ProductReviewsPageSizeOnAccountPage, model.ProductReviewsPageSizeOnAccountPage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(catalogSettings, x => x.ExportImportProductAttributes, model.ExportImportProductAttributes_OverrideForProject, ProjectScope, false);
            //now settings not overridable per project
            _settingService.SaveSetting(catalogSettings, x => x.IgnoreDiscounts, 0, false);
            _settingService.SaveSetting(catalogSettings, x => x.IgnoreFeaturedProducts, 0, false);
            _settingService.SaveSetting(catalogSettings, x => x.IgnoreAcl, 0, false);
            _settingService.SaveSetting(catalogSettings, x => x.IgnoreProjectLimitations, 0, false);
            _settingService.SaveSetting(catalogSettings, x => x.CacheProductPrices, 0, false);


            //now clear settings cache
            _settingService.ClearCache();

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));

            return RedirectToAction("Catalog");
        }

        #region Sort options

        [HttpPost]
        public ActionResult SortOptionsList(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var catalogSettings = _settingService.LoadSetting<CatalogSettings>();
            var model = new List<SortOptionModel>();
            foreach (int option in Enum.GetValues(typeof(ProductSortingEnum)))
            {
                int value;
                model.Add(new SortOptionModel()
                {
                    Id = option,
                    Name = ((ProductSortingEnum)option).GetLocalizedEnum(_localizationService, _workContext),
                    IsActive = !catalogSettings.ProductSortingEnumDisabled.Contains(option),
                    DisplayOrder = catalogSettings.ProductSortingEnumDisplayOrder.TryGetValue(option, out value) ? value : option
                });
            }
            var gridModel = new DataSourceResult
            {
                Data = model.OrderBy(option => option.DisplayOrder),
                Total = model.Count
            };
            return Json(gridModel);
        }

        [HttpPost]
        public ActionResult SortOptionUpdate(SortOptionModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var catalogSettings = _settingService.LoadSetting<CatalogSettings>(ProjectScope);

            catalogSettings.ProductSortingEnumDisplayOrder[model.Id] = model.DisplayOrder;
            if (model.IsActive && catalogSettings.ProductSortingEnumDisabled.Contains(model.Id))
                catalogSettings.ProductSortingEnumDisabled.Remove(model.Id);
            if (!model.IsActive && !catalogSettings.ProductSortingEnumDisabled.Contains(model.Id))
                catalogSettings.ProductSortingEnumDisabled.Add(model.Id);


            _settingService.SaveSetting(catalogSettings);

            return new NullJsonResult();
        }

        #endregion

        public ActionResult RewardPoints()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var rewardPointsSettings = _settingService.LoadSetting<RewardPointsSettings>(ProjectScope);
            var model = rewardPointsSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.Enabled_OverrideForProject = _settingService.SettingExists(rewardPointsSettings, x => x.Enabled, ProjectScope);
                model.ExchangeRate_OverrideForProject = _settingService.SettingExists(rewardPointsSettings, x => x.ExchangeRate, ProjectScope);
                model.MinimumRewardPointsToUse_OverrideForProject = _settingService.SettingExists(rewardPointsSettings, x => x.MinimumRewardPointsToUse, ProjectScope);
                model.PointsForRegistration_OverrideForProject = _settingService.SettingExists(rewardPointsSettings, x => x.PointsForRegistration, ProjectScope);
                model.PointsForPurchases_OverrideForProject = _settingService.SettingExists(rewardPointsSettings, x => x.PointsForPurchases_Amount, ProjectScope) ||
                    _settingService.SettingExists(rewardPointsSettings, x => x.PointsForPurchases_Points, ProjectScope);
                model.PointsForPurchases_Awarded_OverrideForProject = _settingService.SettingExists(rewardPointsSettings, x => x.PointsForPurchases_Awarded, ProjectScope);
                model.PointsForPurchases_Canceled_OverrideForProject = _settingService.SettingExists(rewardPointsSettings, x => x.PointsForPurchases_Canceled, ProjectScope);
                model.DisplayHowMuchWillBeEarned_OverrideForProject = _settingService.SettingExists(rewardPointsSettings, x => x.DisplayHowMuchWillBeEarned, ProjectScope);
                model.PointsForRegistration_OverrideForProject = _settingService.SettingExists(rewardPointsSettings, x => x.PointsForRegistration, ProjectScope);
                model.PageSize_OverrideForProject = _settingService.SettingExists(rewardPointsSettings, x => x.PageSize, ProjectScope);
            }
            var currencySettings = _settingService.LoadSetting<CurrencySettings>(ProjectScope); 
            model.PrimaryProjectCurrencyCode = _currencyService.GetCurrencyById(currencySettings.PrimaryProjectCurrencyId).CurrencyCode;

            return View(model);
        }
        [HttpPost]
        public ActionResult RewardPoints(RewardPointsSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            if (ModelState.IsValid)
            {
                //load settings for a chosen project scope
                var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
                var rewardPointsSettings = _settingService.LoadSetting<RewardPointsSettings>(ProjectScope);
                rewardPointsSettings = model.ToEntity(rewardPointsSettings);

                /* We do not clear cache after each setting update.
                 * This behavior can increase performance because cached settings will not be cleared 
                 * and loaded from database after each update */
                _settingService.SaveSettingOverridablePerProject(rewardPointsSettings, x => x.Enabled, model.Enabled_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(rewardPointsSettings, x => x.ExchangeRate, model.ExchangeRate_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(rewardPointsSettings, x => x.MinimumRewardPointsToUse, model.MinimumRewardPointsToUse_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(rewardPointsSettings, x => x.PointsForRegistration, model.PointsForRegistration_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(rewardPointsSettings, x => x.PointsForPurchases_Amount, model.PointsForPurchases_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(rewardPointsSettings, x => x.PointsForPurchases_Points, model.PointsForPurchases_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(rewardPointsSettings, x => x.PointsForPurchases_Awarded, model.PointsForPurchases_Awarded_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(rewardPointsSettings, x => x.PointsForPurchases_Canceled, model.PointsForPurchases_Canceled_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(rewardPointsSettings, x => x.DisplayHowMuchWillBeEarned, model.DisplayHowMuchWillBeEarned_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(rewardPointsSettings, x => x.PageSize, model.PageSize_OverrideForProject, ProjectScope, false);
                _settingService.SaveSetting(rewardPointsSettings, x => x.PointsAccumulatedForAllProjects, 0, false);

                //now clear settings cache
                _settingService.ClearCache();

                //activity log
                _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            }
            else
            {
                //If we got this far, something failed, redisplay form
                foreach (var modelState in ModelState.Values)
                    foreach (var error in modelState.Errors)
                        ErrorNotification(error.ErrorMessage);
            }
            return RedirectToAction("RewardPoints");
        }




        public ActionResult Order()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();



            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var orderSettings = _settingService.LoadSetting<OrderSettings>(ProjectScope);
            var model = orderSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.IsReOrderAllowed_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.IsReOrderAllowed, ProjectScope);
                model.MinOrderSubtotalAmount_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.MinOrderSubtotalAmount, ProjectScope);
                model.MinOrderSubtotalAmountIncludingTax_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.MinOrderSubtotalAmountIncludingTax, ProjectScope);
                model.MinOrderTotalAmount_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.MinOrderTotalAmount, ProjectScope);
                model.AutoUpdateOrderTotalsOnEditingOrder_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.AutoUpdateOrderTotalsOnEditingOrder, ProjectScope);
                model.AnonymousCheckoutAllowed_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.AnonymousCheckoutAllowed, ProjectScope);
                model.TermsOfServiceOnShoppingCartPage_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.TermsOfServiceOnShoppingCartPage, ProjectScope);
                model.TermsOfServiceOnOrderConfirmPage_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.TermsOfServiceOnOrderConfirmPage, ProjectScope);
                model.OnePageCheckoutEnabled_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.OnePageCheckoutEnabled, ProjectScope);
                model.OnePageCheckoutDisplayOrderTotalsOnPaymentInfoTab_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.OnePageCheckoutDisplayOrderTotalsOnPaymentInfoTab, ProjectScope);
                model.DisableBillingAddressCheckoutStep_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.DisableBillingAddressCheckoutStep, ProjectScope);
                model.DisableOrderCompletedPage_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.DisableOrderCompletedPage, ProjectScope);
                model.AttachPdfInvoiceToOrderPlacedEmail_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.AttachPdfInvoiceToOrderPlacedEmail, ProjectScope);
                model.AttachPdfInvoiceToOrderPaidEmail_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.AttachPdfInvoiceToOrderPaidEmail, ProjectScope);
                model.AttachPdfInvoiceToOrderCompletedEmail_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.AttachPdfInvoiceToOrderCompletedEmail, ProjectScope);
                model.ReturnRequestsEnabled_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.ReturnRequestsEnabled, ProjectScope);
                model.ReturnRequestNumberMask_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.ReturnRequestNumberMask, ProjectScope);
                model.NumberOfDaysReturnRequestAvailable_OverrideForProject = _settingService.SettingExists(orderSettings, x => x.NumberOfDaysReturnRequestAvailable, ProjectScope);
            }

            var currencySettings = _settingService.LoadSetting<CurrencySettings>(ProjectScope);
            model.PrimaryProjectCurrencyCode = _currencyService.GetCurrencyById(currencySettings.PrimaryProjectCurrencyId).CurrencyCode;

            //gift card activation/deactivation
            model.GiftCards_Activated_OrderStatuses = OrderStatus.Pending.ToSelectList(false).ToList();
            model.GiftCards_Activated_OrderStatuses.Insert(0, new SelectListItem { Text = "---", Value = "0" });
            model.GiftCards_Deactivated_OrderStatuses = OrderStatus.Pending.ToSelectList(false).ToList();
            model.GiftCards_Deactivated_OrderStatuses.Insert(0, new SelectListItem { Text = "---", Value = "0" });
            
            //order ident
            model.OrderIdent = _maintenanceService.GetTableIdent<Order>();

            return View(model);
        }
        [HttpPost]
        public ActionResult Order(OrderSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            if (ModelState.IsValid)
            {
                //load settings for a chosen project scope
                var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
                var orderSettings = _settingService.LoadSetting<OrderSettings>(ProjectScope);
                orderSettings = model.ToEntity(orderSettings);

                /* We do not clear cache after each setting update.
                 * This behavior can increase performance because cached settings will not be cleared 
                 * and loaded from database after each update */
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.IsReOrderAllowed, model.IsReOrderAllowed_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.MinOrderSubtotalAmount, model.MinOrderSubtotalAmount_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.MinOrderSubtotalAmountIncludingTax, model.MinOrderSubtotalAmountIncludingTax_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.MinOrderTotalAmount, model.MinOrderTotalAmount_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.AutoUpdateOrderTotalsOnEditingOrder, model.AutoUpdateOrderTotalsOnEditingOrder_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.AnonymousCheckoutAllowed, model.AnonymousCheckoutAllowed_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.TermsOfServiceOnShoppingCartPage, model.TermsOfServiceOnShoppingCartPage_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.TermsOfServiceOnOrderConfirmPage, model.TermsOfServiceOnOrderConfirmPage_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.OnePageCheckoutEnabled, model.OnePageCheckoutEnabled_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.OnePageCheckoutDisplayOrderTotalsOnPaymentInfoTab, model.OnePageCheckoutDisplayOrderTotalsOnPaymentInfoTab_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.DisableBillingAddressCheckoutStep, model.DisableBillingAddressCheckoutStep_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.DisableOrderCompletedPage, model.DisableOrderCompletedPage_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.AttachPdfInvoiceToOrderPlacedEmail, model.AttachPdfInvoiceToOrderPlacedEmail_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.AttachPdfInvoiceToOrderPaidEmail, model.AttachPdfInvoiceToOrderPaidEmail_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.AttachPdfInvoiceToOrderCompletedEmail, model.AttachPdfInvoiceToOrderCompletedEmail_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.ReturnRequestsEnabled, model.ReturnRequestsEnabled_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.NumberOfDaysReturnRequestAvailable, model.NumberOfDaysReturnRequestAvailable_OverrideForProject, ProjectScope, false);
                _settingService.SaveSetting(orderSettings, x => x.GiftCards_Activated_OrderStatusId, 0, false);
                _settingService.SaveSetting(orderSettings, x => x.GiftCards_Deactivated_OrderStatusId, 0, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.ReturnRequestsEnabled, model.ReturnRequestsEnabled_OverrideForProject, ProjectScope, false);
                _settingService.SaveSettingOverridablePerProject(orderSettings, x => x.ReturnRequestNumberMask, model.ReturnRequestNumberMask_OverrideForProject, ProjectScope, false);
               
                //now clear settings cache
                _settingService.ClearCache();
                
                //order ident
                if (model.OrderIdent.HasValue)
                {
                    try
                    {
                        _maintenanceService.SetTableIdent<Order>(model.OrderIdent.Value);
                    }
                    catch (Exception exc)
                    {
                        ErrorNotification(exc.Message);
                    }
                }

                //activity log
                _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            }
            else
            {
                //If we got this far, something failed, redisplay form
                foreach (var modelState in ModelState.Values)
                    foreach (var error in modelState.Errors)
                        ErrorNotification(error.ErrorMessage);
            }

            //selected tab
            SaveSelectedTabName();

            return RedirectToAction("Order");
        }

        #region Return request reasons

        public ActionResult ReturnRequestReasonList()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //we just redirect a user to the order settings page

            //select "return request" tab
            SaveSelectedTabName("tab-returnrequest");
            return RedirectToAction("Order", "Setting");
        }
        [HttpPost]
        public ActionResult ReturnRequestReasonList(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var reasons = _returnRequestService.GetAllReturnRequestReasons();
            var gridModel = new DataSourceResult
            {
                Data = reasons.Select(x => x.ToModel()),
                Total = reasons.Count
            };
            return Json(gridModel);
        }
        //create
        public ActionResult ReturnRequestReasonCreate()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var model = new ReturnRequestReasonModel();
            //locales
            AddLocales(_languageService, model.Locales);
            return View(model);
        }
        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult ReturnRequestReasonCreate(ReturnRequestReasonModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            if (ModelState.IsValid)
            {
                var rrr = model.ToEntity();
                _returnRequestService.InsertReturnRequestReason(rrr);
                //locales
                UpdateLocales(rrr, model);

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.Order.ReturnRequestReasons.Added"));
                return continueEditing ? RedirectToAction("ReturnRequestReasonEdit", new { id = rrr.Id }) : RedirectToAction("ReturnRequestReasonList");
            }

            //If we got this far, something failed, redisplay form
            return View(model);
        }
        //edit
        public ActionResult ReturnRequestReasonEdit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var rrr = _returnRequestService.GetReturnRequestReasonById(id);
            if (rrr == null)
                //No reason found with the specified id
                return RedirectToAction("ReturnRequestReasonList");

            var model = rrr.ToModel();
            //locales
            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.Name = rrr.GetLocalized(x => x.Name, languageId, false, false);
            });
            return View(model);
        }
        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult ReturnRequestReasonEdit(ReturnRequestReasonModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var rrr = _returnRequestService.GetReturnRequestReasonById(model.Id);
            if (rrr == null)
                //No reason found with the specified id
                return RedirectToAction("ReturnRequestReasonList");

            if (ModelState.IsValid)
            {
                rrr = model.ToEntity(rrr);
                _returnRequestService.UpdateReturnRequestReason(rrr);
                //locales
                UpdateLocales(rrr, model);

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.Order.ReturnRequestReasons.Updated"));
                if (continueEditing)
                {
                    //selected tab
                    SaveSelectedTabName();

                    return RedirectToAction("ReturnRequestReasonEdit", new { id = rrr.Id });
                }
                return RedirectToAction("ReturnRequestReasonList");
            }

            //If we got this far, something failed, redisplay form
            return View(model);
        }
        //delete
        [HttpPost]
        public ActionResult ReturnRequestReasonDelete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var rrr = _returnRequestService.GetReturnRequestReasonById(id);
            _returnRequestService.DeleteReturnRequestReason(rrr);

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.Order.ReturnRequestReasons.Deleted"));
            return RedirectToAction("ReturnRequestReasonList");
        }

        #endregion

        #region Return request actions

        public ActionResult ReturnRequestActionList()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //we just redirect a user to the order settings page

            //select "return request" tab
            SaveSelectedTabName("tab-returnrequest");
            return RedirectToAction("Order", "Setting");
        }
        [HttpPost]
        public ActionResult ReturnRequestActionList(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var actions = _returnRequestService.GetAllReturnRequestActions();
            var gridModel = new DataSourceResult
            {
                Data = actions.Select(x => x.ToModel()),
                Total = actions.Count
            };
            return Json(gridModel);
        }
        //create
        public ActionResult ReturnRequestActionCreate()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var model = new ReturnRequestActionModel();
            //locales
            AddLocales(_languageService, model.Locales);
            return View(model);
        }
        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult ReturnRequestActionCreate(ReturnRequestActionModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            if (ModelState.IsValid)
            {
                var rra = model.ToEntity();
                _returnRequestService.InsertReturnRequestAction(rra);
                //locales
                UpdateLocales(rra, model);

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.Order.ReturnRequestActions.Added"));
                return continueEditing ? RedirectToAction("ReturnRequestActionEdit", new { id = rra.Id }) : RedirectToAction("ReturnRequestActionList");
            }

            //If we got this far, something failed, redisplay form
            return View(model);
        }
        //edit
        public ActionResult ReturnRequestActionEdit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var rra = _returnRequestService.GetReturnRequestActionById(id);
            if (rra == null)
                //No action found with the specified id
                return RedirectToAction("ReturnRequestActionList");

            var model = rra.ToModel();
            //locales
            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.Name = rra.GetLocalized(x => x.Name, languageId, false, false);
            });
            return View(model);
        }
        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult ReturnRequestActionEdit(ReturnRequestActionModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var rra = _returnRequestService.GetReturnRequestActionById(model.Id);
            if (rra == null)
                //No action found with the specified id
                return RedirectToAction("ReturnRequestActionList");

            if (ModelState.IsValid)
            {
                rra = model.ToEntity(rra);
                _returnRequestService.UpdateReturnRequestAction(rra);
                //locales
                UpdateLocales(rra, model);

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.Order.ReturnRequestActions.Updated"));
                if (continueEditing)
                {
                    //selected tab
                    SaveSelectedTabName();

                    return RedirectToAction("ReturnRequestActionEdit", new { id = rra.Id });
                }
                return RedirectToAction("ReturnRequestActionList");
            }

            //If we got this far, something failed, redisplay form
            return View(model);
        }
        //delete
        [HttpPost]
        public ActionResult ReturnRequestActionDelete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var rra = _returnRequestService.GetReturnRequestActionById(id);
            _returnRequestService.DeleteReturnRequestAction(rra);

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.Order.ReturnRequestActions.Deleted"));
            return RedirectToAction("ReturnRequestActionList");
        }

        #endregion





        public ActionResult ShoppingCart()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var shoppingCartSettings = _settingService.LoadSetting<ShoppingCartSettings>(ProjectScope);
            var model = shoppingCartSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.DisplayCartAfterAddingProduct_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.DisplayCartAfterAddingProduct, ProjectScope);
                model.DisplayWishlistAfterAddingProduct_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.DisplayWishlistAfterAddingProduct, ProjectScope);
                model.MaximumShoppingCartItems_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.MaximumShoppingCartItems, ProjectScope);
                model.MaximumWishlistItems_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.MaximumWishlistItems, ProjectScope);
                model.AllowOutOfStockItemsToBeAddedToWishlist_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.AllowOutOfStockItemsToBeAddedToWishlist, ProjectScope);
                model.MoveItemsFromWishlistToCart_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.MoveItemsFromWishlistToCart, ProjectScope);
                model.ShowProductImagesOnShoppingCart_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.ShowProductImagesOnShoppingCart, ProjectScope);
                model.ShowProductImagesOnWishList_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.ShowProductImagesOnWishList, ProjectScope);
                model.ShowDiscountBox_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.ShowDiscountBox, ProjectScope);
                model.ShowGiftCardBox_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.ShowGiftCardBox, ProjectScope);
                model.CrossSellsNumber_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.CrossSellsNumber, ProjectScope);
                model.EmailWishlistEnabled_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.EmailWishlistEnabled, ProjectScope);
                model.AllowAnonymousUsersToEmailWishlist_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.AllowAnonymousUsersToEmailWishlist, ProjectScope);
                model.MiniShoppingCartEnabled_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.MiniShoppingCartEnabled, ProjectScope);
                model.ShowProductImagesInMiniShoppingCart_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.ShowProductImagesInMiniShoppingCart, ProjectScope);
                model.MiniShoppingCartProductNumber_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.MiniShoppingCartProductNumber, ProjectScope);
                model.AllowCartItemEditing_OverrideForProject = _settingService.SettingExists(shoppingCartSettings, x => x.AllowCartItemEditing, ProjectScope);
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult ShoppingCart(ShoppingCartSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var shoppingCartSettings = _settingService.LoadSetting<ShoppingCartSettings>(ProjectScope);
            shoppingCartSettings = model.ToEntity(shoppingCartSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.DisplayCartAfterAddingProduct, model.DisplayCartAfterAddingProduct_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.DisplayWishlistAfterAddingProduct, model.DisplayWishlistAfterAddingProduct_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.MaximumShoppingCartItems, model.MaximumShoppingCartItems_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.MaximumWishlistItems, model.MaximumWishlistItems_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.AllowOutOfStockItemsToBeAddedToWishlist, model.AllowOutOfStockItemsToBeAddedToWishlist_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.MoveItemsFromWishlistToCart, model.MoveItemsFromWishlistToCart_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.ShowProductImagesOnShoppingCart, model.ShowProductImagesOnShoppingCart_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.ShowProductImagesOnWishList, model.ShowProductImagesOnWishList_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.ShowDiscountBox, model.ShowDiscountBox_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.ShowGiftCardBox, model.ShowGiftCardBox_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.CrossSellsNumber, model.CrossSellsNumber_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.EmailWishlistEnabled, model.EmailWishlistEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.AllowAnonymousUsersToEmailWishlist, model.AllowAnonymousUsersToEmailWishlist_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.MiniShoppingCartEnabled, model.MiniShoppingCartEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.ShowProductImagesInMiniShoppingCart, model.ShowProductImagesInMiniShoppingCart_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.MiniShoppingCartProductNumber, model.MiniShoppingCartProductNumber_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(shoppingCartSettings, x => x.AllowCartItemEditing, model.AllowCartItemEditing_OverrideForProject, ProjectScope, false);
            
            //now clear settings cache
            _settingService.ClearCache();
            

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("ShoppingCart");
        }




        public ActionResult Media()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var mediaSettings = _settingService.LoadSetting<MediaSettings>(ProjectScope);
            var model = mediaSettings.ToModel();
            model.ActiveProjectScopeConfiguration = ProjectScope;
            if (ProjectScope > 0)
            {
                model.AvatarPictureSize_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.AvatarPictureSize, ProjectScope);
                model.ProductThumbPictureSize_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.ProductThumbPictureSize, ProjectScope);
                model.ProductDetailsPictureSize_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.ProductDetailsPictureSize, ProjectScope);
                model.ProductThumbPictureSizeOnProductDetailsPage_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.ProductThumbPictureSizeOnProductDetailsPage, ProjectScope);
                model.AssociatedProductPictureSize_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.AssociatedProductPictureSize, ProjectScope);
                model.CategoryThumbPictureSize_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.CategoryThumbPictureSize, ProjectScope);
                model.ManufacturerThumbPictureSize_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.ManufacturerThumbPictureSize, ProjectScope);
                model.VendorThumbPictureSize_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.VendorThumbPictureSize, ProjectScope);
                model.CartThumbPictureSize_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.CartThumbPictureSize, ProjectScope);
                model.MiniCartThumbPictureSize_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.MiniCartThumbPictureSize, ProjectScope);
                model.MaximumImageSize_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.MaximumImageSize, ProjectScope);
                model.MultipleThumbDirectories_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.MultipleThumbDirectories, ProjectScope);
                model.DefaultImageQuality_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.DefaultImageQuality, ProjectScope);
                model.ImportProductImagesUsingHash_OverrideForProject = _settingService.SettingExists(mediaSettings, x => x.ImportProductImagesUsingHash, ProjectScope);
            }
            model.PicturesStoredIntoDatabase = _pictureService.StoreInDb;
            return View(model);
        }
        [HttpPost]
        [FormValueRequired("save")]
        public ActionResult Media(MediaSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var mediaSettings = _settingService.LoadSetting<MediaSettings>(ProjectScope);
            mediaSettings = model.ToEntity(mediaSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.AvatarPictureSize, model.AvatarPictureSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.ProductThumbPictureSize, model.ProductThumbPictureSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.ProductDetailsPictureSize, model.ProductDetailsPictureSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.ProductThumbPictureSizeOnProductDetailsPage, model.ProductThumbPictureSizeOnProductDetailsPage_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.AssociatedProductPictureSize, model.AssociatedProductPictureSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.CategoryThumbPictureSize, model.CategoryThumbPictureSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.ManufacturerThumbPictureSize, model.ManufacturerThumbPictureSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.VendorThumbPictureSize, model.VendorThumbPictureSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.CartThumbPictureSize, model.CartThumbPictureSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.MiniCartThumbPictureSize, model.MiniCartThumbPictureSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.MaximumImageSize, model.MaximumImageSize_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.MultipleThumbDirectories, model.MultipleThumbDirectories_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.DefaultImageQuality, model.DefaultImageQuality_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(mediaSettings, x => x.ImportProductImagesUsingHash, model.ImportProductImagesUsingHash_OverrideForProject, ProjectScope, false);
            
            //now clear settings cache
            _settingService.ClearCache();
            
            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Media");
        }
        [HttpPost, ActionName("Media")]
        [FormValueRequired("change-picture-storage")]
        public ActionResult ChangePictureStorage()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            _pictureService.StoreInDb = !_pictureService.StoreInDb;

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Media");
        }



        public ActionResult CustomerUser()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var customerSettings = _settingService.LoadSetting<CustomerSettings>(ProjectScope);
            var addressSettings = _settingService.LoadSetting<AddressSettings>(ProjectScope);
            var dateTimeSettings = _settingService.LoadSetting<DateTimeSettings>(ProjectScope);
            var externalAuthenticationSettings = _settingService.LoadSetting<ExternalAuthenticationSettings>(ProjectScope);

            //merge settings
            var model = new CustomerUserSettingsModel();
            model.CustomerSettings = customerSettings.ToModel();
            model.AddressSettings = addressSettings.ToModel();

            model.DateTimeSettings.AllowCustomersToSetTimeZone = dateTimeSettings.AllowCustomersToSetTimeZone;
            model.DateTimeSettings.DefaultProjectTimeZoneId = _dateTimeHelper.DefaultProjectTimeZone.Id;
            foreach (TimeZoneInfo timeZone in _dateTimeHelper.GetSystemTimeZones())
            {
                model.DateTimeSettings.AvailableTimeZones.Add(new SelectListItem
                    {
                        Text = timeZone.DisplayName,
                        Value = timeZone.Id,
                        Selected = timeZone.Id.Equals(_dateTimeHelper.DefaultProjectTimeZone.Id, StringComparison.InvariantCultureIgnoreCase)
                    });
            }

            model.ExternalAuthenticationSettings.AutoRegisterEnabled = externalAuthenticationSettings.AutoRegisterEnabled;

            return View(model);
        }
        [HttpPost]
        public ActionResult CustomerUser(CustomerUserSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var customerSettings = _settingService.LoadSetting<CustomerSettings>(ProjectScope);
            var addressSettings = _settingService.LoadSetting<AddressSettings>(ProjectScope);
            var dateTimeSettings = _settingService.LoadSetting<DateTimeSettings>(ProjectScope);
            var externalAuthenticationSettings = _settingService.LoadSetting<ExternalAuthenticationSettings>(ProjectScope);

            customerSettings = model.CustomerSettings.ToEntity(customerSettings);
            _settingService.SaveSetting(customerSettings);

            addressSettings = model.AddressSettings.ToEntity(addressSettings);
            _settingService.SaveSetting(addressSettings);

            dateTimeSettings.DefaultProjectTimeZoneId = model.DateTimeSettings.DefaultProjectTimeZoneId;
            dateTimeSettings.AllowCustomersToSetTimeZone = model.DateTimeSettings.AllowCustomersToSetTimeZone;
            _settingService.SaveSetting(dateTimeSettings);

            externalAuthenticationSettings.AutoRegisterEnabled = model.ExternalAuthenticationSettings.AutoRegisterEnabled;
            _settingService.SaveSetting(externalAuthenticationSettings);

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));

            //selected tab
            SaveSelectedTabName();

            return RedirectToAction("CustomerUser");
        }






        public ActionResult GeneralCommon()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            var model = new GeneralCommonSettingsModel();
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            model.ActiveProjectScopeConfiguration = ProjectScope;
            //project information
            var projectInformationSettings = _settingService.LoadSetting<ProjectInformationSettings>(ProjectScope);
            var commonSettings = _settingService.LoadSetting<CommonSettings>(ProjectScope);
            model.ProjectInformationSettings.ProjectClosed = projectInformationSettings.ProjectClosed;
            //themes
            model.ProjectInformationSettings.DefaultProjectTheme = projectInformationSettings.DefaultProjectTheme;
            model.ProjectInformationSettings.AvailableProjectThemes = _themeProvider
                .GetThemeConfigurations()
                .Select(x => new GeneralCommonSettingsModel.ProjectInformationSettingsModel.ThemeConfigurationModel
                {
                    ThemeTitle = x.ThemeTitle,
                    ThemeName = x.ThemeName,
                    PreviewImageUrl = x.PreviewImageUrl,
                    PreviewText = x.PreviewText,
                    SupportRtl = x.SupportRtl,
                    Selected = x.ThemeName.Equals(projectInformationSettings.DefaultProjectTheme, StringComparison.InvariantCultureIgnoreCase)
                })
                .ToList();
            model.ProjectInformationSettings.AllowCustomerToSelectTheme = projectInformationSettings.AllowCustomerToSelectTheme;
            model.ProjectInformationSettings.LogoPictureId = projectInformationSettings.LogoPictureId;
            //EU Cookie law
            model.ProjectInformationSettings.DisplayEuCookieLawWarning = projectInformationSettings.DisplayEuCookieLawWarning;
            //social pages
            model.ProjectInformationSettings.FacebookLink = projectInformationSettings.FacebookLink;
            model.ProjectInformationSettings.TwitterLink = projectInformationSettings.TwitterLink;
            model.ProjectInformationSettings.YoutubeLink = projectInformationSettings.YoutubeLink;
            model.ProjectInformationSettings.GooglePlusLink = projectInformationSettings.GooglePlusLink;
            //contact us
            model.ProjectInformationSettings.SubjectFieldOnContactUsForm = commonSettings.SubjectFieldOnContactUsForm;
            model.ProjectInformationSettings.UseSystemEmailForContactUsForm = commonSettings.UseSystemEmailForContactUsForm;
            //sitemap
            model.ProjectInformationSettings.SitemapEnabled = commonSettings.SitemapEnabled;
            model.ProjectInformationSettings.SitemapIncludeCategories = commonSettings.SitemapIncludeCategories;
            model.ProjectInformationSettings.SitemapIncludeManufacturers = commonSettings.SitemapIncludeManufacturers;
            model.ProjectInformationSettings.SitemapIncludeProducts = commonSettings.SitemapIncludeProducts;

            //override settings
            if (ProjectScope > 0)
            {
                model.ProjectInformationSettings.ProjectClosed_OverrideForProject = _settingService.SettingExists(projectInformationSettings, x => x.ProjectClosed, ProjectScope);
                model.ProjectInformationSettings.DefaultProjectTheme_OverrideForProject = _settingService.SettingExists(projectInformationSettings, x => x.DefaultProjectTheme, ProjectScope);
                model.ProjectInformationSettings.AllowCustomerToSelectTheme_OverrideForProject = _settingService.SettingExists(projectInformationSettings, x => x.AllowCustomerToSelectTheme, ProjectScope);
                model.ProjectInformationSettings.LogoPictureId_OverrideForProject = _settingService.SettingExists(projectInformationSettings, x => x.LogoPictureId, ProjectScope);
                model.ProjectInformationSettings.DisplayEuCookieLawWarning_OverrideForProject = _settingService.SettingExists(projectInformationSettings, x => x.DisplayEuCookieLawWarning, ProjectScope);
                model.ProjectInformationSettings.FacebookLink_OverrideForProject = _settingService.SettingExists(projectInformationSettings, x => x.FacebookLink, ProjectScope);
                model.ProjectInformationSettings.TwitterLink_OverrideForProject = _settingService.SettingExists(projectInformationSettings, x => x.TwitterLink, ProjectScope);
                model.ProjectInformationSettings.YoutubeLink_OverrideForProject = _settingService.SettingExists(projectInformationSettings, x => x.YoutubeLink, ProjectScope);
                model.ProjectInformationSettings.GooglePlusLink_OverrideForProject = _settingService.SettingExists(projectInformationSettings, x => x.GooglePlusLink, ProjectScope);
                model.ProjectInformationSettings.SubjectFieldOnContactUsForm_OverrideForProject = _settingService.SettingExists(commonSettings, x => x.SubjectFieldOnContactUsForm, ProjectScope);
                model.ProjectInformationSettings.UseSystemEmailForContactUsForm_OverrideForProject = _settingService.SettingExists(commonSettings, x => x.UseSystemEmailForContactUsForm, ProjectScope);
                model.ProjectInformationSettings.SitemapEnabled_OverrideForProject = _settingService.SettingExists(commonSettings, x => x.SitemapEnabled, ProjectScope);
                model.ProjectInformationSettings.SitemapIncludeCategories_OverrideForProject = _settingService.SettingExists(commonSettings, x => x.SitemapIncludeCategories, ProjectScope);
                model.ProjectInformationSettings.SitemapIncludeManufacturers_OverrideForProject = _settingService.SettingExists(commonSettings, x => x.SitemapIncludeManufacturers, ProjectScope);
                model.ProjectInformationSettings.SitemapIncludeProducts_OverrideForProject = _settingService.SettingExists(commonSettings, x => x.SitemapIncludeProducts, ProjectScope);
            }

            //seo settings
            var seoSettings = _settingService.LoadSetting<SeoSettings>(ProjectScope);
            model.SeoSettings.PageTitleSeparator = seoSettings.PageTitleSeparator;
            model.SeoSettings.PageTitleSeoAdjustment = (int)seoSettings.PageTitleSeoAdjustment;
            model.SeoSettings.PageTitleSeoAdjustmentValues = seoSettings.PageTitleSeoAdjustment.ToSelectList();
            model.SeoSettings.DefaultTitle = seoSettings.DefaultTitle;
            model.SeoSettings.DefaultMetaKeywords = seoSettings.DefaultMetaKeywords;
            model.SeoSettings.DefaultMetaDescription = seoSettings.DefaultMetaDescription;
            model.SeoSettings.GenerateProductMetaDescription = seoSettings.GenerateProductMetaDescription;
            model.SeoSettings.ConvertNonWesternChars = seoSettings.ConvertNonWesternChars;
            model.SeoSettings.CanonicalUrlsEnabled = seoSettings.CanonicalUrlsEnabled;
            model.SeoSettings.WwwRequirement = (int)seoSettings.WwwRequirement;
            model.SeoSettings.WwwRequirementValues = seoSettings.WwwRequirement.ToSelectList();
            model.SeoSettings.EnableJsBundling = seoSettings.EnableJsBundling;
            model.SeoSettings.EnableCssBundling = seoSettings.EnableCssBundling;
            model.SeoSettings.TwitterMetaTags = seoSettings.TwitterMetaTags;
            model.SeoSettings.OpenGraphMetaTags = seoSettings.OpenGraphMetaTags;
            model.SeoSettings.CustomHeadTags = seoSettings.CustomHeadTags;
            //override settings
            if (ProjectScope > 0)
            {
                model.SeoSettings.PageTitleSeparator_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.PageTitleSeparator, ProjectScope);
                model.SeoSettings.PageTitleSeoAdjustment_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.PageTitleSeoAdjustment, ProjectScope);
                model.SeoSettings.DefaultTitle_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.DefaultTitle, ProjectScope);
                model.SeoSettings.DefaultMetaKeywords_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.DefaultMetaKeywords, ProjectScope);
                model.SeoSettings.DefaultMetaDescription_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.DefaultMetaDescription, ProjectScope);
                model.SeoSettings.GenerateProductMetaDescription_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.GenerateProductMetaDescription, ProjectScope);
                model.SeoSettings.ConvertNonWesternChars_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.ConvertNonWesternChars, ProjectScope);
                model.SeoSettings.CanonicalUrlsEnabled_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.CanonicalUrlsEnabled, ProjectScope);
                model.SeoSettings.WwwRequirement_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.WwwRequirement, ProjectScope);
                model.SeoSettings.EnableJsBundling_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.EnableJsBundling, ProjectScope);
                model.SeoSettings.EnableCssBundling_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.EnableCssBundling, ProjectScope);
                model.SeoSettings.TwitterMetaTags_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.TwitterMetaTags, ProjectScope);
                model.SeoSettings.OpenGraphMetaTags_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.OpenGraphMetaTags, ProjectScope);
                model.SeoSettings.CustomHeadTags_OverrideForProject = _settingService.SettingExists(seoSettings, x => x.CustomHeadTags, ProjectScope);
            }
            
            //security settings
            var securitySettings = _settingService.LoadSetting<SecuritySettings>(ProjectScope);
            var captchaSettings = _settingService.LoadSetting<CaptchaSettings>(ProjectScope);
            model.SecuritySettings.EncryptionKey = securitySettings.EncryptionKey;
            if (securitySettings.AdminAreaAllowedIpAddresses != null)
                for (int i = 0; i < securitySettings.AdminAreaAllowedIpAddresses.Count; i++)
                {
                    model.SecuritySettings.AdminAreaAllowedIpAddresses += securitySettings.AdminAreaAllowedIpAddresses[i];
                    if (i != securitySettings.AdminAreaAllowedIpAddresses.Count - 1)
                        model.SecuritySettings.AdminAreaAllowedIpAddresses += ",";
                }
            model.SecuritySettings.ForceSslForAllPages = securitySettings.ForceSslForAllPages;
            model.SecuritySettings.EnableXsrfProtectionForAdminArea = securitySettings.EnableXsrfProtectionForAdminArea;
            model.SecuritySettings.EnableXsrfProtectionForPublicProject = securitySettings.EnableXsrfProtectionForPublicProject;
            model.SecuritySettings.HoneypotEnabled = securitySettings.HoneypotEnabled;
            model.SecuritySettings.CaptchaEnabled = captchaSettings.Enabled;
            model.SecuritySettings.CaptchaShowOnLoginPage = captchaSettings.ShowOnLoginPage;
            model.SecuritySettings.CaptchaShowOnRegistrationPage = captchaSettings.ShowOnRegistrationPage;
            model.SecuritySettings.CaptchaShowOnContactUsPage = captchaSettings.ShowOnContactUsPage;
            model.SecuritySettings.CaptchaShowOnEmailWishlistToFriendPage = captchaSettings.ShowOnEmailWishlistToFriendPage;
            model.SecuritySettings.CaptchaShowOnEmailProductToFriendPage = captchaSettings.ShowOnEmailProductToFriendPage;
            model.SecuritySettings.CaptchaShowOnBlogCommentPage = captchaSettings.ShowOnBlogCommentPage;
            model.SecuritySettings.CaptchaShowOnNewsCommentPage = captchaSettings.ShowOnNewsCommentPage;
            model.SecuritySettings.CaptchaShowOnProductReviewPage = captchaSettings.ShowOnProductReviewPage;
            model.SecuritySettings.CaptchaShowOnApplyVendorPage = captchaSettings.ShowOnApplyVendorPage;
            model.SecuritySettings.ReCaptchaVersion = captchaSettings.ReCaptchaVersion;
            model.SecuritySettings.AvailableReCaptchaVersions = ReCaptchaVersion.Version1.ToSelectList(false).ToList();
            model.SecuritySettings.ReCaptchaPublicKey = captchaSettings.ReCaptchaPublicKey;
            model.SecuritySettings.ReCaptchaPrivateKey = captchaSettings.ReCaptchaPrivateKey;

            //PDF settings
            var pdfSettings = _settingService.LoadSetting<PdfSettings>(ProjectScope);
            model.PdfSettings.LetterPageSizeEnabled = pdfSettings.LetterPageSizeEnabled;
            model.PdfSettings.LogoPictureId = pdfSettings.LogoPictureId;
            model.PdfSettings.DisablePdfInvoicesForPendingOrders = pdfSettings.DisablePdfInvoicesForPendingOrders;
            model.PdfSettings.InvoiceFooterTextColumn1 = pdfSettings.InvoiceFooterTextColumn1;
            model.PdfSettings.InvoiceFooterTextColumn2 = pdfSettings.InvoiceFooterTextColumn2;
            //override settings
            if (ProjectScope > 0)
            {
                model.PdfSettings.LetterPageSizeEnabled_OverrideForProject = _settingService.SettingExists(pdfSettings, x => x.LetterPageSizeEnabled, ProjectScope);
                model.PdfSettings.LogoPictureId_OverrideForProject = _settingService.SettingExists(pdfSettings, x => x.LogoPictureId, ProjectScope);
                model.PdfSettings.DisablePdfInvoicesForPendingOrders_OverrideForProject = _settingService.SettingExists(pdfSettings, x => x.DisablePdfInvoicesForPendingOrders, ProjectScope);
                model.PdfSettings.InvoiceFooterTextColumn1_OverrideForProject = _settingService.SettingExists(pdfSettings, x => x.InvoiceFooterTextColumn1, ProjectScope);
                model.PdfSettings.InvoiceFooterTextColumn2_OverrideForProject = _settingService.SettingExists(pdfSettings, x => x.InvoiceFooterTextColumn2, ProjectScope);
            }

            //localization
            var localizationSettings = _settingService.LoadSetting<LocalizationSettings>(ProjectScope);
            model.LocalizationSettings.UseImagesForLanguageSelection = localizationSettings.UseImagesForLanguageSelection;
            model.LocalizationSettings.SeoFriendlyUrlsForLanguagesEnabled = localizationSettings.SeoFriendlyUrlsForLanguagesEnabled;
            model.LocalizationSettings.AutomaticallyDetectLanguage = localizationSettings.AutomaticallyDetectLanguage;
            model.LocalizationSettings.LoadAllLocaleRecordsOnStartup = localizationSettings.LoadAllLocaleRecordsOnStartup;
            model.LocalizationSettings.LoadAllLocalizedPropertiesOnStartup = localizationSettings.LoadAllLocalizedPropertiesOnStartup;
            model.LocalizationSettings.LoadAllUrlRecordsOnStartup = localizationSettings.LoadAllUrlRecordsOnStartup;

            //full-text support
            model.FullTextSettings.Supported = _fulltextService.IsFullTextSupported();
            model.FullTextSettings.Enabled = commonSettings.UseFullTextSearch;
            model.FullTextSettings.SearchMode = (int)commonSettings.FullTextMode;
            model.FullTextSettings.SearchModeValues = commonSettings.FullTextMode.ToSelectList();


            return View(model);
        }
        [HttpPost]
        [FormValueRequired("save")]
        public ActionResult GeneralCommon(GeneralCommonSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen project scope
            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);

            //project information settings
            var projectInformationSettings = _settingService.LoadSetting<ProjectInformationSettings>(ProjectScope);
            var commonSettings = _settingService.LoadSetting<CommonSettings>(ProjectScope);
            projectInformationSettings.ProjectClosed = model.ProjectInformationSettings.ProjectClosed;
            projectInformationSettings.DefaultProjectTheme = model.ProjectInformationSettings.DefaultProjectTheme;
            projectInformationSettings.AllowCustomerToSelectTheme = model.ProjectInformationSettings.AllowCustomerToSelectTheme;
            projectInformationSettings.LogoPictureId = model.ProjectInformationSettings.LogoPictureId;
            //EU Cookie law
            projectInformationSettings.DisplayEuCookieLawWarning = model.ProjectInformationSettings.DisplayEuCookieLawWarning;
            //social pages
            projectInformationSettings.FacebookLink = model.ProjectInformationSettings.FacebookLink;
            projectInformationSettings.TwitterLink = model.ProjectInformationSettings.TwitterLink;
            projectInformationSettings.YoutubeLink = model.ProjectInformationSettings.YoutubeLink;
            projectInformationSettings.GooglePlusLink = model.ProjectInformationSettings.GooglePlusLink;
            //contact us
            commonSettings.SubjectFieldOnContactUsForm = model.ProjectInformationSettings.SubjectFieldOnContactUsForm;
            commonSettings.UseSystemEmailForContactUsForm = model.ProjectInformationSettings.UseSystemEmailForContactUsForm;
            //sitemap
            commonSettings.SitemapEnabled = model.ProjectInformationSettings.SitemapEnabled;
            commonSettings.SitemapIncludeCategories = model.ProjectInformationSettings.SitemapIncludeCategories;
            commonSettings.SitemapIncludeManufacturers = model.ProjectInformationSettings.SitemapIncludeManufacturers;
            commonSettings.SitemapIncludeProducts = model.ProjectInformationSettings.SitemapIncludeProducts;

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */

            _settingService.SaveSettingOverridablePerProject(projectInformationSettings, x => x.ProjectClosed, model.ProjectInformationSettings.ProjectClosed_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(projectInformationSettings, x => x.DefaultProjectTheme, model.ProjectInformationSettings.DefaultProjectTheme_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(projectInformationSettings, x => x.AllowCustomerToSelectTheme, model.ProjectInformationSettings.AllowCustomerToSelectTheme_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(projectInformationSettings, x => x.LogoPictureId, model.ProjectInformationSettings.LogoPictureId_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(projectInformationSettings, x => x.DisplayEuCookieLawWarning, model.ProjectInformationSettings.DisplayEuCookieLawWarning_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(projectInformationSettings, x => x.FacebookLink, model.ProjectInformationSettings.FacebookLink_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(projectInformationSettings, x => x.TwitterLink, model.ProjectInformationSettings.TwitterLink_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(projectInformationSettings, x => x.YoutubeLink, model.ProjectInformationSettings.YoutubeLink_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(projectInformationSettings, x => x.GooglePlusLink, model.ProjectInformationSettings.GooglePlusLink_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(commonSettings, x => x.SubjectFieldOnContactUsForm, model.ProjectInformationSettings.SubjectFieldOnContactUsForm_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(commonSettings, x => x.UseSystemEmailForContactUsForm, model.ProjectInformationSettings.UseSystemEmailForContactUsForm_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(commonSettings, x => x.SitemapEnabled, model.ProjectInformationSettings.SitemapEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(commonSettings, x => x.SitemapIncludeCategories, model.ProjectInformationSettings.SitemapIncludeCategories_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(commonSettings, x => x.SitemapIncludeManufacturers, model.ProjectInformationSettings.SitemapIncludeManufacturers_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(commonSettings, x => x.SitemapIncludeProducts, model.ProjectInformationSettings.SitemapIncludeProducts_OverrideForProject, ProjectScope, false);

            //now clear settings cache
            _settingService.ClearCache();



            //seo settings
            var seoSettings = _settingService.LoadSetting<SeoSettings>(ProjectScope);
            seoSettings.PageTitleSeparator = model.SeoSettings.PageTitleSeparator;
            seoSettings.PageTitleSeoAdjustment = (PageTitleSeoAdjustment)model.SeoSettings.PageTitleSeoAdjustment;
            seoSettings.DefaultTitle = model.SeoSettings.DefaultTitle;
            seoSettings.DefaultMetaKeywords = model.SeoSettings.DefaultMetaKeywords;
            seoSettings.DefaultMetaDescription = model.SeoSettings.DefaultMetaDescription;
            seoSettings.GenerateProductMetaDescription = model.SeoSettings.GenerateProductMetaDescription;
            seoSettings.ConvertNonWesternChars = model.SeoSettings.ConvertNonWesternChars;
            seoSettings.CanonicalUrlsEnabled = model.SeoSettings.CanonicalUrlsEnabled;
            seoSettings.WwwRequirement = (WwwRequirement)model.SeoSettings.WwwRequirement;
            seoSettings.EnableJsBundling = model.SeoSettings.EnableJsBundling;
            seoSettings.EnableCssBundling = model.SeoSettings.EnableCssBundling;
            seoSettings.TwitterMetaTags = model.SeoSettings.TwitterMetaTags;
            seoSettings.OpenGraphMetaTags = model.SeoSettings.OpenGraphMetaTags;
            seoSettings.CustomHeadTags = model.SeoSettings.CustomHeadTags;

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.PageTitleSeparator, model.SeoSettings.PageTitleSeparator_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.PageTitleSeoAdjustment, model.SeoSettings.PageTitleSeoAdjustment_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.DefaultTitle, model.SeoSettings.DefaultTitle_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.DefaultMetaKeywords, model.SeoSettings.DefaultMetaKeywords_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.DefaultMetaDescription, model.SeoSettings.DefaultMetaDescription_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.GenerateProductMetaDescription, model.SeoSettings.GenerateProductMetaDescription_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.ConvertNonWesternChars, model.SeoSettings.ConvertNonWesternChars_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.CanonicalUrlsEnabled, model.SeoSettings.CanonicalUrlsEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.WwwRequirement, model.SeoSettings.WwwRequirement_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.EnableJsBundling, model.SeoSettings.EnableJsBundling_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.EnableCssBundling, model.SeoSettings.EnableCssBundling_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.TwitterMetaTags, model.SeoSettings.TwitterMetaTags_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.OpenGraphMetaTags, model.SeoSettings.OpenGraphMetaTags_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(seoSettings, x => x.CustomHeadTags, model.SeoSettings.CustomHeadTags_OverrideForProject, ProjectScope, false);
            
            //now clear settings cache
            _settingService.ClearCache();



            //security settings
            var securitySettings = _settingService.LoadSetting<SecuritySettings>(ProjectScope);
            var captchaSettings = _settingService.LoadSetting<CaptchaSettings>(ProjectScope);
            if (securitySettings.AdminAreaAllowedIpAddresses == null)
                securitySettings.AdminAreaAllowedIpAddresses = new List<string>();
            securitySettings.AdminAreaAllowedIpAddresses.Clear();
            if (!String.IsNullOrEmpty(model.SecuritySettings.AdminAreaAllowedIpAddresses))
                foreach (string s in model.SecuritySettings.AdminAreaAllowedIpAddresses.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    if (!String.IsNullOrWhiteSpace(s))
                        securitySettings.AdminAreaAllowedIpAddresses.Add(s.Trim());
            securitySettings.ForceSslForAllPages = model.SecuritySettings.ForceSslForAllPages;
            securitySettings.EnableXsrfProtectionForAdminArea = model.SecuritySettings.EnableXsrfProtectionForAdminArea;
            securitySettings.EnableXsrfProtectionForPublicProject = model.SecuritySettings.EnableXsrfProtectionForPublicProject;
            securitySettings.HoneypotEnabled = model.SecuritySettings.HoneypotEnabled;
            _settingService.SaveSetting(securitySettings);
            captchaSettings.Enabled = model.SecuritySettings.CaptchaEnabled;
            captchaSettings.ShowOnLoginPage = model.SecuritySettings.CaptchaShowOnLoginPage;
            captchaSettings.ShowOnRegistrationPage = model.SecuritySettings.CaptchaShowOnRegistrationPage;
            captchaSettings.ShowOnContactUsPage = model.SecuritySettings.CaptchaShowOnContactUsPage;
            captchaSettings.ShowOnEmailWishlistToFriendPage = model.SecuritySettings.CaptchaShowOnEmailWishlistToFriendPage;
            captchaSettings.ShowOnEmailProductToFriendPage = model.SecuritySettings.CaptchaShowOnEmailProductToFriendPage;
            captchaSettings.ShowOnBlogCommentPage = model.SecuritySettings.CaptchaShowOnBlogCommentPage;
            captchaSettings.ShowOnNewsCommentPage = model.SecuritySettings.CaptchaShowOnNewsCommentPage;
            captchaSettings.ShowOnProductReviewPage = model.SecuritySettings.CaptchaShowOnProductReviewPage;
            captchaSettings.ShowOnApplyVendorPage = model.SecuritySettings.CaptchaShowOnApplyVendorPage;
            captchaSettings.ReCaptchaVersion = model.SecuritySettings.ReCaptchaVersion;
            captchaSettings.ReCaptchaPublicKey = model.SecuritySettings.ReCaptchaPublicKey;
            captchaSettings.ReCaptchaPrivateKey = model.SecuritySettings.ReCaptchaPrivateKey;
            _settingService.SaveSetting(captchaSettings);
            if (captchaSettings.Enabled &&
                (String.IsNullOrWhiteSpace(captchaSettings.ReCaptchaPublicKey) || String.IsNullOrWhiteSpace(captchaSettings.ReCaptchaPrivateKey)))
            {
                //captcha is enabled but the keys are not entered
                ErrorNotification("Captcha is enabled but the appropriate keys are not entered");
            }

            //PDF settings
            var pdfSettings = _settingService.LoadSetting<PdfSettings>(ProjectScope);
            pdfSettings.LetterPageSizeEnabled = model.PdfSettings.LetterPageSizeEnabled;
            pdfSettings.LogoPictureId = model.PdfSettings.LogoPictureId;
            pdfSettings.DisablePdfInvoicesForPendingOrders = model.PdfSettings.DisablePdfInvoicesForPendingOrders;
            pdfSettings.InvoiceFooterTextColumn1 = model.PdfSettings.InvoiceFooterTextColumn1;
            pdfSettings.InvoiceFooterTextColumn2 = model.PdfSettings.InvoiceFooterTextColumn2;
            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            
            _settingService.SaveSettingOverridablePerProject(pdfSettings, x => x.LetterPageSizeEnabled, model.PdfSettings.LetterPageSizeEnabled_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(pdfSettings, x => x.LogoPictureId, model.PdfSettings.LogoPictureId_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(pdfSettings, x => x.DisablePdfInvoicesForPendingOrders, model.PdfSettings.DisablePdfInvoicesForPendingOrders_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(pdfSettings, x => x.InvoiceFooterTextColumn1, model.PdfSettings.InvoiceFooterTextColumn1_OverrideForProject, ProjectScope, false);
            _settingService.SaveSettingOverridablePerProject(pdfSettings, x => x.InvoiceFooterTextColumn2, model.PdfSettings.InvoiceFooterTextColumn2_OverrideForProject, ProjectScope, false);
           
            //now clear settings cache
            _settingService.ClearCache();




            //localization settings
            var localizationSettings = _settingService.LoadSetting<LocalizationSettings>(ProjectScope);
            localizationSettings.UseImagesForLanguageSelection = model.LocalizationSettings.UseImagesForLanguageSelection;
            if (localizationSettings.SeoFriendlyUrlsForLanguagesEnabled != model.LocalizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
            {
                localizationSettings.SeoFriendlyUrlsForLanguagesEnabled = model.LocalizationSettings.SeoFriendlyUrlsForLanguagesEnabled;
                //clear cached values of routes
                System.Web.Routing.RouteTable.Routes.ClearSeoFriendlyUrlsCachedValueForRoutes();
            }
            localizationSettings.AutomaticallyDetectLanguage = model.LocalizationSettings.AutomaticallyDetectLanguage;
            localizationSettings.LoadAllLocaleRecordsOnStartup = model.LocalizationSettings.LoadAllLocaleRecordsOnStartup;
            localizationSettings.LoadAllLocalizedPropertiesOnStartup = model.LocalizationSettings.LoadAllLocalizedPropertiesOnStartup;
            localizationSettings.LoadAllUrlRecordsOnStartup = model.LocalizationSettings.LoadAllUrlRecordsOnStartup;
            _settingService.SaveSetting(localizationSettings);

            //full-text
            commonSettings.FullTextMode = (FulltextSearchMode)model.FullTextSettings.SearchMode;
            _settingService.SaveSetting(commonSettings);

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            
            return RedirectToAction("GeneralCommon");
        }
        [HttpPost, ActionName("GeneralCommon")]
        [FormValueRequired("changeencryptionkey")]
        public ActionResult ChangeEncryptionKey(GeneralCommonSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var securitySettings = _settingService.LoadSetting<SecuritySettings>(ProjectScope);

            try
            {
                if (model.SecuritySettings.EncryptionKey == null)
                    model.SecuritySettings.EncryptionKey = "";

                model.SecuritySettings.EncryptionKey = model.SecuritySettings.EncryptionKey.Trim();

                var newEncryptionPrivateKey = model.SecuritySettings.EncryptionKey;
                if (String.IsNullOrEmpty(newEncryptionPrivateKey) || newEncryptionPrivateKey.Length != 16)
                    throw new SDFException(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.EncryptionKey.TooShort"));

                string oldEncryptionPrivateKey = securitySettings.EncryptionKey;
                if (oldEncryptionPrivateKey == newEncryptionPrivateKey)
                    throw new SDFException(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.EncryptionKey.TheSame"));

                //update encrypted order info
                var orders = _orderService.SearchOrders();
                foreach (var order in orders)
                {
                    string decryptedCardType = _encryptionService.DecryptText(order.CardType, oldEncryptionPrivateKey);
                    string decryptedCardName = _encryptionService.DecryptText(order.CardName, oldEncryptionPrivateKey);
                    string decryptedCardNumber = _encryptionService.DecryptText(order.CardNumber, oldEncryptionPrivateKey);
                    string decryptedMaskedCreditCardNumber = _encryptionService.DecryptText(order.MaskedCreditCardNumber, oldEncryptionPrivateKey);
                    string decryptedCardCvv2 = _encryptionService.DecryptText(order.CardCvv2, oldEncryptionPrivateKey);
                    string decryptedCardExpirationMonth = _encryptionService.DecryptText(order.CardExpirationMonth, oldEncryptionPrivateKey);
                    string decryptedCardExpirationYear = _encryptionService.DecryptText(order.CardExpirationYear, oldEncryptionPrivateKey);

                    string encryptedCardType = _encryptionService.EncryptText(decryptedCardType, newEncryptionPrivateKey);
                    string encryptedCardName = _encryptionService.EncryptText(decryptedCardName, newEncryptionPrivateKey);
                    string encryptedCardNumber = _encryptionService.EncryptText(decryptedCardNumber, newEncryptionPrivateKey);
                    string encryptedMaskedCreditCardNumber = _encryptionService.EncryptText(decryptedMaskedCreditCardNumber, newEncryptionPrivateKey);
                    string encryptedCardCvv2 = _encryptionService.EncryptText(decryptedCardCvv2, newEncryptionPrivateKey);
                    string encryptedCardExpirationMonth = _encryptionService.EncryptText(decryptedCardExpirationMonth, newEncryptionPrivateKey);
                    string encryptedCardExpirationYear = _encryptionService.EncryptText(decryptedCardExpirationYear, newEncryptionPrivateKey);

                    order.CardType = encryptedCardType;
                    order.CardName = encryptedCardName;
                    order.CardNumber = encryptedCardNumber;
                    order.MaskedCreditCardNumber = encryptedMaskedCreditCardNumber;
                    order.CardCvv2 = encryptedCardCvv2;
                    order.CardExpirationMonth = encryptedCardExpirationMonth;
                    order.CardExpirationYear = encryptedCardExpirationYear;
                    _orderService.UpdateOrder(order);
                }

                //update user information
                //optimization - load only users with PasswordFormat.Encrypted
                var customers = _customerService.GetAllCustomersByPasswordFormat(PasswordFormat.Encrypted);
                foreach (var customer in customers)
                {
                    string decryptedPassword = _encryptionService.DecryptText(customer.Password, oldEncryptionPrivateKey);
                    string encryptedPassword = _encryptionService.EncryptText(decryptedPassword, newEncryptionPrivateKey);

                    customer.Password = encryptedPassword;
                    _customerService.UpdateCustomer(customer);
                }

                securitySettings.EncryptionKey = newEncryptionPrivateKey;
                _settingService.SaveSetting(securitySettings);
                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.EncryptionKey.Changed"));
            }
            catch (Exception exc)
            {
                ErrorNotification(exc);
            }
            return RedirectToAction("GeneralCommon");
        }
        [HttpPost, ActionName("GeneralCommon")]
        [FormValueRequired("togglefulltext")]
        public ActionResult ToggleFullText(GeneralCommonSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var ProjectScope = this.GetActiveProjectScopeConfiguration(_projectService, _workContext);
            var commonSettings = _settingService.LoadSetting<CommonSettings>(ProjectScope);
            try
            {
                if (! _fulltextService.IsFullTextSupported())
                    throw new SDFException(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.FullTextSettings.NotSupported"));

                if (commonSettings.UseFullTextSearch)
                {
                    _fulltextService.DisableFullText();

                    commonSettings.UseFullTextSearch = false;
                    _settingService.SaveSetting(commonSettings);

                    SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.FullTextSettings.Disabled"));
                }
                else
                {
                    _fulltextService.EnableFullText();

                    commonSettings.UseFullTextSearch = true;
                    _settingService.SaveSetting(commonSettings);

                    SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.FullTextSettings.Enabled"));
                }
            }
            catch (Exception exc)
            {
                ErrorNotification(exc);
            }
            
            return RedirectToAction("GeneralCommon");
        }




        //all settings
        public ActionResult AllSettings()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();
            
            return View();
        }
        [HttpPost]
        //do not validate request token (XSRF)
        //for some reasons it does not work with "filtering" support
        [AdminAntiForgery(true)] 
        public ActionResult AllSettings(DataSourceRequest command, AllSettingsListModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var query = _settingService.GetAllSettings().AsQueryable();

            if (!string.IsNullOrEmpty(model.SearchSettingName))
                query = query.Where(s => s.Name.ToLowerInvariant().Contains(model.SearchSettingName.ToLowerInvariant()));
            if (!string.IsNullOrEmpty(model.SearchSettingValue))
                query = query.Where(s => s.Value.ToLowerInvariant().Contains(model.SearchSettingValue.ToLowerInvariant()));

            var settings = query.ToList()
                .Select(x =>
                            {
                                string Projectname;
                                if (x.ProjectId == 0)
                                {
                                    Projectname = _localizationService.GetResource("Admin.Configuration.Settings.AllSettings.Fields.ProjectName.AllProjects");
                                }
                                else
                                {
                                    var project = _projectService.GetProjectById(x.ProjectId);
                                    Projectname = project != null ? project.Name : "Unknown";
                                }
                                var settingModel = new SettingModel
                                {
                                    Id = x.Id,
                                    Name = x.Name,
                                    Value = x.Value,
                                    Project = Projectname,
                                    ProjectId = x.ProjectId
                                };
                                return settingModel;
                            })
                .AsQueryable();

            var gridModel = new DataSourceResult
            {
                Data = settings.PagedForCommand(command).ToList(),
                Total = settings.Count()
            };

            return Json(gridModel);
        }
        [HttpPost]
        public ActionResult SettingUpdate(SettingModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            if (model.Name != null)
                model.Name = model.Name.Trim();
            if (model.Value != null)
                model.Value = model.Value.Trim();

            if (!ModelState.IsValid)
            {
                return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
            }

            var setting = _settingService.GetSettingById(model.Id);
            if (setting == null)
                return Content("No setting could be loaded with the specified ID");

            var projectId = model.ProjectId;

            if (!setting.Name.Equals(model.Name, StringComparison.InvariantCultureIgnoreCase) ||
                setting.ProjectId != projectId)
            {
                //setting name or project has been changed
                _settingService.DeleteSetting(setting);
            }

            _settingService.SetSetting(model.Name, model.Value, projectId);

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            return new NullJsonResult();
        }
        [HttpPost]
        public ActionResult SettingAdd([Bind(Exclude = "Id")] SettingModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            if (model.Name != null)
                model.Name = model.Name.Trim();
            if (model.Value != null)
                model.Value = model.Value.Trim();

            if (!ModelState.IsValid)
            {
                return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
            }
            var projectId = model.ProjectId;
            _settingService.SetSetting(model.Name, model.Value, projectId);

            //activity log
            _customerActivityService.InsertActivity("AddNewSetting", _localizationService.GetResource("ActivityLog.AddNewSetting"), model.Name);

            return new NullJsonResult();
        }
        [HttpPost]
        public ActionResult SettingDelete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var setting = _settingService.GetSettingById(id);
            if (setting == null)
                throw new ArgumentException("No setting found with the specified id");
            _settingService.DeleteSetting(setting);

            //activity log
            _customerActivityService.InsertActivity("DeleteSetting", _localizationService.GetResource("ActivityLog.DeleteSetting"), setting.Name);

            return new NullJsonResult();
        }

        #endregion
    }
}
